[英]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):
我有简单的学生请求模型,我想在其中验证电话号码(只允许使用 9 位数字):
public class StudentRequestBodyModel {
@NotNull
private String name;
@NotNull
private String surname;
private Date dateOfBirth;
@PhoneNumber
private String phoneNumber;
private String studentCardID;
}
and @PhoneValid interface:和@PhoneValid 接口:
@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.当我在 regexr.com 上检查该正则表达式时,它只匹配 9 位数字,但是当我通过邮递员发送它时,例如“123456789”,我收到错误消息。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.