您还可以创建自己的休眠验证注释。
在下面的示例中,我创建了一个带有 name 的验证注释EnsureNumber
。带有此注释的字段将使用类的isValid
方法进行验证EnsureNumberValidator
。
@Constraint(validatedBy = EnsureNumberValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface EnsureNumber {
String message() default "{PasswordMatch}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
boolean decimal() default false;
}
public class EnsureNumberValidator implements ConstraintValidator<EnsureNumber, Object> {
private EnsureNumber ensureNumber;
@Override
public void initialize(EnsureNumber constraintAnnotation) {
this.ensureNumber = constraintAnnotation;
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
// Check the state of the Adminstrator.
if (value == null) {
return false;
}
// Initialize it.
String regex = ensureNumber.decimal() ? "-?[0-9][0-9\\.\\,]*" : "-?[0-9]+";
String data = String.valueOf(value);
return data.matches(regex);
}
}
可以这样使用
@NotEmpty
@Size(min = 6, max = 6)
@EnsureNumber
private String number1;
@NotEmpty
@Size(min = 6, max = 6)
@EnsureNumber(message = "Field number2 is not valid.")
private String number2;
@NotEmpty
@Size(min = 6, max = 6)
@EnsureNumber(decimal = true, message = "Field number is not valid.")
private String number3;