您可以使用 Bean Validation (JSR-303) 定义自己的自定义验证,例如这里是简单的自定义邮政编码验证,通过使用自定义注释进行注释,您可以轻松验证:
@Documented
@Constraint(validatedBy = ZipCodeValidator.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ZipCode {
String message() default "zip code must be five numeric characters";
Class<?>[] groups() default {};
Class<?>[] payload() default {};
}
和自定义验证类,而不是,你可以使用你的自定义 bean,比如<YourAnnotationClassName,TypeWhichIsBeingValidated>
public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {
@Override
public void initialize(ZipCode zipCode) {
}
@Override
public boolean isValid(String string, ConstraintValidatorContext context) {
if (string.length() != 5)
return false;
for (char c : string.toCharArray()) {
if (!Character.isDigit(c))
return false;
}
return true;
}
}
这是它的用法:
public class Address{
@ZipCode
private String zip;
}