如何进行javax验证只显示一条错误消息

bla*_*ank 1 java spring-mvc hibernate-validator bean-validation

假设我在这样的字段上进行验证:

@NotEmpty
@Digits(integer = 3, fraction = 0)
private String code;
Run Code Online (Sandbox Code Playgroud)

目前,如果我将表单字段留空,我会使用Spring MVC和Hibernate验证.有没有办法只显示@NotEmpty消息?

Har*_*rdy 5

如果您想坚持使用Bean验证规范,则需要使用组序列.只有组序列才能保证有序约束评估在第一个错误时停止.就像是:

@GroupSequence({ First.class, Second.class })
public class MyBean {
   @NotEmpty(groups = First.class)
   @Digits(integer = 3, fraction = 0, groups = Second.class)
   private String code;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果仅使用默认组序列进行验证并获取"javax.validation.GroupDefinitionException:MyBean必须是重新定义的默认组序列的一部分",请确保将bean包含在@GroupSequence中,即:@GroupSequence({First.class,Second .class,MyBean.class}). (3认同)