每个字段约束都应由不同的验证者注释处理,换句话说,不建议对一个字段进行其他字段的验证注释检查。跨领域验证应在课程级别进行。另外,JSR-303第2.2节表示同一类型的多个验证的首选方法是通过注释列表。这样可以在每次匹配中指定错误消息。
例如,验证通用格式:
@FieldMatch.List({ @FieldMatch(first = "password", second = "/confirm/iPassword", message = "The password fields must match"), @FieldMatch(first = "email", second = "/confirm/iEmail", message = "The email fields must match")})public class UserRegistrationForm { @NotNull @Size(min=8, max=25) private String password; @NotNull @Size(min=8, max=25) private String /confirm/iPassword; @NotNull @Email private String email; @NotNull @Email private String /confirm/iEmail;}
注释:
package constraints;import constraints.impl.FieldMatchValidator;import javax.validation.Constraint;import javax.validation.Payload;import java.lang.annotation.documented;import static java.lang.annotation.ElementType.ANNOTATION_TYPE;import static java.lang.annotation.ElementType.TYPE;import java.lang.annotation.Retention;import static java.lang.annotation.RetentionPolicy.RUNTIME;import java.lang.annotation.Target;@Target({TYPE, ANNOTATION_TYPE})@Retention(RUNTIME)@Constraint(validatedBy = FieldMatchValidator.class)@documentedpublic @interface FieldMatch{ String message() default "{constraints.fieldmatch}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String first(); String second(); @Target({TYPE, ANNOTATION_TYPE}) @Retention(RUNTIME) @documented @interface List { FieldMatch[] value(); }}
验证者:
package constraints.impl;import constraints.FieldMatch;import org.apache.commons.beanutils.BeanUtils;import javax.validation.ConstraintValidator;import javax.validation.ConstraintValidatorContext;public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object>{ private String firstFieldName; private String secondFieldName; @Override public void initialize(final FieldMatch constraintAnnotation) { firstFieldName = constraintAnnotation.first(); secondFieldName = constraintAnnotation.second(); } @Override public boolean isValid(final Object value, final ConstraintValidatorContext context) { try { final Object firstObj = BeanUtils.getProperty(value, firstFieldName); final Object secondObj = BeanUtils.getProperty(value, secondFieldName); return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj); } catch (final Exception ignore) { // ignore } return true; }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)