Lulex97
Lulex97

Reputation: 271

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.

Upvotes: 0

Views: 49

Answers (1)

Adrian Smith
Adrian Smith

Reputation: 17593

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();

Upvotes: 2

Related Questions