To build a custom validation example you need to:
1-Create an Interface
2-Create a class that implements ConstraintValidator
3-Use the custom validation in the Bean
Step 1:
@Documented
@Constraint(validatedBy=PhoneConstraintValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String message() default "{Phone}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Step 2:
public class PhoneConstraintValidator implements ConstraintValidator<Phone, String> {
@Override
public void initialize(Phone phone) {
}
@Override
public boolean isValid(String phoneField, ConstraintValidatorContext cxt) {
if (phoneField == null){
return false;
}
return phoneField.matches("[0-9()-]*");
}
}
Step 3:
@NotEmpty @Phone
private String phoneNumber;
No comments:
Post a Comment