Java 根据hibernate validator中验证失败的内容,自定义验证器是否可以有多条消息?
我有一个自定义验证来检查类中的电子邮件字段 注释界面:Java 根据hibernate validator中验证失败的内容,自定义验证器是否可以有多条消息?,java,spring,hibernate-validator,Java,Spring,Hibernate Validator,我有一个自定义验证来检查类中的电子邮件字段 注释界面: @ReportAsSingleViolation @NotBlank @Email @Target({ CONSTRUCTOR, FIELD, METHOD, PARAMETER, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = CustomEmailValidator.class) @Documented public @interface CustomEm
@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 {};
}
问题是,此错误消息用于验证期间的所有失败,因此即使用户提供了空白字符串,它也会打印该消息。我想做的是,如果验证在
@NotBlank
上失败,则打印一条“必填字段消息”,如果验证在@Email
上失败,则提供一条“无效电子邮件”消息。只有在自定义验证失败时,才会打印CustomEmail.email
消息。另外,在我的注释界面中,@NotBlank
和@Email
是按顺序出现还是随机运行。那么,首先运行的任何验证都会作为错误返回?我的验证要求它们按照列出的顺序运行@NotBlank
,然后是@Email
,然后是CustomEmail。您可以创建一个枚举,定义预期错误的类型,然后使用其值从配置中检索正确的错误消息。差不多
/**
<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;
};
请注意,在自定义约束中没有定义顺序。即使您先列出@NotBlank,然后列出@Email,也无法保证订单。Java本身不定义注释中的任何顺序。如果要定义订单,需要使用组和/或组序列。在这种情况下,也不能使用组合约束,因为会忽略组合约束上的组定义。仅应用主约束的组 关闭
@reportAssingeViolation
。对于每个违规行为,您将得到一个ConstraintViolation
,并且可以相应地工作
至于顺序,按照@Hardy的回答。更正@Hardy,问题最终是分组顺序和
@NotBlank
和@Email
。此外,@EmersonFarrugia是正确的,因为删除@reportassingelivalition
将显示发生的每个错误。我通过在模型对象内部定义一个组序列来解决了我的问题,我将@CustomEmail
应用于该对象。强制默认先运行,自定义后运行。我将@NotBlank
和@Email
从@CustomEmail
中移出,并将它们放在类成员上。这意味着我的@CustomEmail
只有在默认设置失败时才会运行,并且在一个成员上没有多次失败的情况下,每个错误类型都会收到不同的消息。
CustomEmail.email=The provided email can not be added to the account.
/**
<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...