【发布时间】:2014-02-28 17:43:22
【问题描述】:
我有一个自定义验证来检查课程中的电子邮件字段。
注解接口:
@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。
【问题讨论】:
标签: java spring hibernate-validator