number validation in spring boot

Viewed 7245

I have declared an annotation in my model, for a 10 digit mobile number but it is still accepting more than 10 digits

@NotNull
@Min(10)
public String mobileNumber;

when we entered any mobile number then accept 10 digit mobile number only

4 Answers

Use @Size to define the length of the input.

Use of @Min is different.

Also use @NotBlank instead of @NotNull as @NotBlank will check

  • String is not null
  • Trimmed length is greater than zero

If you are using hibernate then you can use :

@Length(max = 10)

to restrict the length of max to 10. This @Length is hibernate specific. You can also use :

@Size(min = 10, max = 10)

to set the condition to validate minimum and maximum length as per your requirment.

The below code will work for you

@NotBlank(message = "mobileNumber is required")
@Size(min = 10, max = 10)
public String mobileNumber;

For mobile numbers validation, I suggest writing your Custom Validator annotation. Since mobile numbers can have different valid patterns. To start, you define an annotation type:

@Target({ElementType.FIELD , ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PhoneNumberValidator.class)

public @interface PhoneNumberValidationAnnotationName {
     String message() default "Message to returned on validation failure";

      Class<?>[] groups() default {} ;

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

After that, you define your validation logic in a separate class:

public class PhoneNumberValidator implements 
      ConstraintValidator<PhoneNumberValidationAnnotationName, String> {

//Here you define your phone number valid pattern
//you can put country code, number length, any specific pattern
private final String PATTERN = "(country-code)[0-9]{8}" ;

@Override
public boolean isValid(String phone, ConstraintValidatorContext context) {
    
    if(Pattern.matches(FIRST_PATTERN , phone)) {
        return true ;
    }

    return false ;
    
    }   
}

For more info, click here

Related