在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;

然后我输入一个空值。

它说,“不能为空,长度必须在2到35之间”

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


问题答案:

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

@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 {};
}

重要的部分是@ReportAsSingleViolation批注