您还可以创建自己的休眠验证批注。
在下面的示例中,我创建了一个名为 的验证注释。具有此注释的字段将使用类的方法进行验证。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;