[英]In Spring MVC validation, Is it possible to show only one error message per field at a time?
例,
我有
@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注釋
為您的字段使用自定義約束。 例如,將使用注釋@StringField
。
@Target(ElementType.FIELD)
@Constraint(validatedBy = StringFieldValidator.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface StringField {
String message() default "Wrong data of string field";
String messageNotEmpty() default "Field can't be empty";
String messageLength() default "Wrong length of field";
boolean notEmpty() default false;
int min() default 0;
int max() default Integer.MAX_VALUE;
Class<?>[] groups() default {};
Class<?>[] payload() default {};
}
然后在StringFieldValidator
類中創建一些邏輯。 該類由接口ConstraintValidator <A extends Annotation, T>
。
public class StringFieldValidator implements ConstraintValidator<StringField, String> {
private Boolean notEmpty;
private Integer min;
private Integer max;
private String messageNotEmpty;
private String messageLength;
@Override
public void initialize(StringField field) {
notEmpty = field.notEmpty();
min = field.min();
max = field.max();
messageNotBlank = field.messageNotEmpty();
messageLength = field.messageLength();
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
context.disableDefaultConstraintViolation();
if (notEmpty && value.isEmpty()) {
context.buildConstraintViolationWithTemplate(messageNotEmpty).addConstraintViolation();
return false;
}
if ((min > 0 || max < Integer.MAX_VALUE) && (value.length() < min || value.length() > max)) {
context.buildConstraintViolationWithTemplate(messageLength).addConstraintViolation();
return false;
}
return true;
}
}
然后你可以使用注釋:
@StringField(notEmpty = true, min = 6, max = 64,
messageNotEmpty = "Field can't be empty",
messageLength = "Field should be 6 to 64 characters size")
畢竟,您將只有一個錯誤消息以正確的順序顯示。
更好的解決方案是在錯誤消息中添加一些標記,以便格式化,例如<br />
,並使用CSS類格式化整個消息。 正如Bozho評論中所指出的,用戶應該知道一切不正確的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.