Home > Back-end >  Custom mobile validator using spring boot
Custom mobile validator using spring boot

Time:12-15

Hi Guys I am trying to create a custom mobile validator. But each time whether the regex is true or not it is returning false. Can you help me with that

public class MobileValidator implements ConstraintValidator<MobileValidation, String> {


    public boolean isValid(String value, ConstraintValidatorContext context) {
        Pattern regex = Pattern.compile("^[6-9]\\d{9}$");
        Matcher match = regex.matcher(value);
        if(value != null && !value.equals(match.matches())){
            System.out.println(context);
            return false;
        }

        return true;
    }

CodePudding user response:

public boolean isValid(String value, ConstraintValidatorContext context) {
Pattern regex = Pattern.compile("^[6-9]\\d{9}$");
Matcher match = regex.matcher(value);
if (StringUtil.isNotBlank(value) && match.matches()) {
    System.out.println(context);
    return false;
}

return true;

}

CodePudding user response:

match.matches() returns a boolean that says whether the pattern matched or not; you don't need to compare it with the result, you should just use the boolean:

public boolean isValid(String value, ConstraintValidatorContext context) {
    Pattern regex = Pattern.compile("^[6-9]\\d{9}$");
    Matcher match = regex.matcher(value);
    if (match.matches()) {
        System.out.println(context);
        return false;
    }

    return true;
}

CodePudding user response:

Function Pattern.matcher not return value string, please use:

public boolean isValid(String value, ConstraintValidatorContext context) { Pattern pattern = Pattern.compile("^[6-9]\d{9}$");

return null != value && pattern.matcher(value).matches(); }

  • Related