简体   繁体   中英

Pattern matcher returns false

I have problem with pattern and matcher. I have simple student request model where I want to valid phone number (only numbers with 9 digits are allowed):

public class StudentRequestBodyModel {
      @NotNull
      private String name;
      @NotNull
      private String surname;
      private Date dateOfBirth;
      @PhoneNumber
      private String phoneNumber;
      private String studentCardID;
}

and @PhoneValid interface:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PhoneNumberValidator.class)
public @interface PhoneNumber {
    String message() default "Incorrect phone number. Only 9 digits allowed";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

PhoneNumberValidator:

public class PhoneNumberValidator implements ConstraintValidator<PhoneNumber, String> {

@Override
public boolean isValid(String phoneNumber, ConstraintValidatorContext context) {
    return Pattern.compile(phoneNumber).matcher("^[0-9]{9}$").matches();
}

}

When I check that regex on regexr.com it works, matches only number with 9 digits but when I send it by postman, for example "123456789" I am getting error.

The pattern and string you want to match against are the wrong way around. You need:

return Pattern.compile("^[0-9]{9}$").matcher(phoneNumber).matches();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM