20

I have a entity called User and I want to validate a mobile number field

The mobile number field is not mandatory it can be left blank but it should be a 10 digit number.

If the user enters any value less then 10 digits in length then an error should be thrown.

Below is my User class.

public class User {

    @Size(min=0,max=10)
    private String mobileNo;

}

When I used @Sized annotation as mentioned above, I could validate values that were greater than 10 but if the user entered less than 10 digits no error was raised.

My requirement is, if user left the mobileNo field blank that is valid but if a value is entered then the validation should ensure that the number entered is 10 digits and 10 digits only.

Which annotation I should use for this requirement?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Ankur Raiyani
  • 1,509
  • 5
  • 21
  • 49

6 Answers6

38

@Size(min=10,max=10) would do the job if by blank you mean null.

If you don't put @NotNull annotation, null value would pass validation.

If your blank means empty String then you need to use @Pattern validator:

@Pattern(regexp="(^$|[0-9]{10})")

this matches either empty string or 10 digits number.

Piotr Kochański
  • 21,862
  • 7
  • 70
  • 77
  • But because most MVC frameworks will bind an empty string to a field when the corresponding text box is left blank, that may not actually solve the problem. I addressed a very similar problem by writing my own validation annotations. Another thing you could consider is using a @Pattern and regular expression to validate the field. – Kent Rancourt May 19 '12 at 22:47
  • 1
    How we can check if Phone Number don't have hyphens in between? For Ex:012-345-6789, such values should be validated –  Oct 05 '15 at 15:41
12

For those who are looking for a custom validator for phone numbers using libphonenumber

PhoneNumber.java libphonenumber requires locale for validation so we need to create a custom class for storing phone and regioncode

public class PhoneNumber {

  @NotEmpty
  private String value;

  @NotEmpty
  private String locale;
}

@Phone Annotation Will be used to annotate fields for validation

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = PhoneNumberValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String locale() default "";

String message() default "Invalid phone number";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

PhoneNumberValidator.java It will check phone's validity for the provided region code

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PhoneNumberValidator implements ConstraintValidator<Phone, PhoneNumber> {

    @Override
    public void initialize(Phone constraintAnnotation) {

    }

    @Override
    public boolean isValid(PhoneNumber phoneNumber, ConstraintValidatorContext context) {
        if(phoneNumber.getLocale()==null || phoneNumber.getValue()==null){
            return false;
        }
        try{
            PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
            return phoneNumberUtil.isValidNumber(phoneNumberUtil.parse(phoneNumber.getValue(), phoneNumber.getLocale()));
        }
        catch (NumberParseException e){
            return false;
        }
      }
    }

Usage

@Phone
private PhoneNumber phone;
Raj
  • 370
  • 4
  • 6
6

Maybe you could improve the suggested response with the use of libphonenumber from Google Code in order to validate your phonenumbers.

BendaThierry.com
  • 2,080
  • 1
  • 15
  • 17
  • This looks like a great library. Will check it out to validate and convert numbers. – djmj May 31 '16 at 06:07
0

Maybe it's too late to answer, but there seems to be an annotation in Hibernate Validator for exactly this purpose.

It's the @Digits(integer=, fraction=) annotation. If you specify the integer attribute to be 10, then the string will have exactly 10 digits. It can be applied to BigInteger (other number types) and also to strings. More about it can be found here.

0

This will work, it supports BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types.

@Range(min = 10,max= 10, message = "phone_no should be exact 10 characters." )

It checks whether the annotated value lies between (inclusive) the specified minimum and maximum.

EvanK
  • 1,052
  • 1
  • 10
  • 23
0

Maybe it's too late to answer you can do this thing with Hibernate Annotation.

You have to define @Size annotation into your model.

@Size(min = 10, max = 17, message = "Number should have at least 10 or less than 17 digits")

I have taken max 17 digit validation because it also includes international mobile Validation.

By using @Size you can find an error message from the Annotation if you write less than 10 or greater than 17.