When using spring Boot’s own annotations, you need to customize the implementation annotations

For example, verify mobile phone numbers

Check whether the mobile phone number is valid, in fact, this can be done through the regular expression

1. Create an annotation

@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = PhoneValidator.class)
@Documented
public @interface Phone {
    String message(a) default "phone invalid"; Class<? >[] groups()default {};

    Class<? extends Payload>[] payload() default {};
}
Copy the code

2. ImplementConstraintValidatorInterface, rewriteisValid()methods

public class PhoneValidator implements ConstraintValidator<Phone.String> {

    @Override
    public void initialize(Phone constraintAnnotation) {}@Override
    public boolean isValid(String phone, ConstraintValidatorContext context) {
        if (phone == null) return false;
        returnDataConstraintsConst.phonePattern.matcher(phone).matches(); }}Copy the code

3. Use notes

@phone (message = "Phone number format is not correct ")
private String phone;
Copy the code