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