在Spring MVC验证中,是否可以一次只显示每个字段的一条错误消息?

Kev*_*vin 7 java spring spring-mvc

例,

我有

@NotEmpty //tells you 'may not be empty' if the field is empty
@Length(min = 2, max = 35) //tells you 'length must be between 2 and 35' if the field is less than 2 or greater than 35
private String firstName;
Run Code Online (Sandbox Code Playgroud)

然后我输入一个空值.

它说''可能不是空的长度必须在2到35之间'

是否有可能告诉spring每个字段一次验证一个?

Fra*_*man 8

对的,这是可能的.只需像这样创建自己的注释:

@Documented
@Constraint(validatedBy = {})
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
@NotEmpty
@Length(min = 2, max = 35)
public @interface MyAnnotation {

    public abstract String message() default "{mypropertykey}";

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

    public abstract Class<?>[] payload() default {};
}
Run Code Online (Sandbox Code Playgroud)

重要的部分是@ReportAsSingleViolation注释