2014-02-28 135 views
0

我有一個自定義驗證來檢查一個類中的電子郵件字段。基於Hibernate驗證器中驗證失敗的自定義驗證器是否可以有多個消息?

註釋接口:

@ReportAsSingleViolation 
@NotBlank 
@Email 
@Target({ CONSTRUCTOR, FIELD, METHOD, PARAMETER, ANNOTATION_TYPE }) 
@Retention(RUNTIME) 
@Constraint(validatedBy = CustomEmailValidator.class) 
@Documented 
public @interface CustomEmail { 
    String message() default "Failed email validation."; 

    Class<?>[] groups() default {}; 

    Class<? extends Payload>[] payload() default {}; 
} 

CustomEmailValidator類:

public class CustomEmailValidator implements ConstraintValidator<CustomEmail, String> { 

    public void initialize(CustomEmail customEmail) { 
    // nothing to initialize 
    } 

    public boolean isValid(String email, ConstraintValidatorContext arg1) { 
    if (email != null) { 
    String domain = "example.com"; 
    String[] emailParts = email.split("@"); 

     return (emailParts.length == 2 && emailParts[1].equals(domain)); 
    } else { 
     return false; 
    } 
    } 
} 

我使用ValidationMessages.properties文件對所有我的自定義消息。在屬性文件中我使用引用失敗在上面的代碼:

CustomEmail.email=The provided email can not be added to the account. 

的問題是,該錯誤消息用於驗證過程中所有的失敗,因此,即使用戶提供一個空字符串它將打印該消息。我想要做的是如果驗證失敗@NotBlank然後打印一個「必填字段消息」,如果它失敗@Email提供一個「無效的電子郵件」消息。那麼只有當它失敗時,自定義驗證纔會打印CustomEmail.email消息。同樣在我的註釋界面中,@NotBlank@Email按順序發生,或者它們是隨機運行的。那麼,首先運行的驗證是否會返回爲錯誤?我的驗證要求他們按照列出的順序運行@NotBlank,然後按@Email後跟CustomEmail。

回答

0

注意,在您的自定義約束,也沒有定義的順序。即使如此,你首先列出@NotBlank然後@Email,沒有訂單保證。 Java本身並沒有在註釋中定義任何順序。如果你想定義一個訂單,你需要使用組和/或組序列。在這種情況下,您也不能使用組合約束,因爲組合約束上的組定義會被忽略。只有主要約束的組適用。

+0

正確@Hardy,問題最終成爲組序列和'@ NotBlank'和'@ Email'。 @EmersonFarrugia也是正確的,因爲刪除'@ ReportAsSingleViolation'會顯示發生的每一個錯誤。我通過在模型objet中定義一個我正在應用'@ CustomEmail'的組序列來解決我的問題。強制默認運行第一個和最後一個自定義。我把'@ NotBlank'和'@ Email'移出'@ CustomEmail',並把它們放在類成員上。這意味着我的'@ CustomEmail'只有在默認失敗時纔會運行,並且對於每個錯誤類型得到不同的消息,而一個成員沒有多次失敗。 – adtrano

0

您可以創建一個Enum來定義預期錯誤的類型,然後使用它的值從配置中檢索正確的錯誤消息。喜歡的東西

/** 
    <P>Defines the type of email-formatting error message.</P> 
**/ 
public enum EmailErrorTypeIs { 
    /** 
    <P>...</P> 

    @see #INVALID 
    @see #OTHER 
    **/ 
    BLANK, 
    /** 
    <P>...</P> 

    @see #BLANK 
    **/ 
    INVALID, 
    /** 
    <P>...</P> 

    @see #BLANK 
    **/ 
    OTHER; 
}; 

,你會使用這樣的:

if(input == null || input.length() == 0) { 
    throw new IllegalArgumentException(getErrorFromConfig(EmailErrorTypeIs.BLANK)); 
} else if... 
0

關閉@ReportAsSingleViolation。您會針對每項違規行爲獲得ConstraintViolation,並且可以相應地進行工作。

至於命令,下面@哈代的回答。