0

Possible Duplicate:
A comprehensive regex for phone number validation

i want to validate a telephone number field as can be null and if any entered then it should be 10 digits. Does anyone know how I can write the regular expression for such? I'm using the @Pattern annotation to validate the telephone number.
Thanks a lot

Community
  • 1
  • 1
user421607
  • 175
  • 2
  • 4
  • 12

3 Answers3

3
boolean validate(String number) {
    return number == null || Pattern.compile("^\\d{10}$").find());
}
AlexR
  • 114,158
  • 16
  • 130
  • 208
  • Cant we check the can null in a regular expression using an or operator cos im using the @Pattern annotation to validate the telephone number – user421607 Aug 25 '11 at 11:11
  • From the javadoc (http://download.oracle.com/javaee/6/api/javax/validation/constraints/Pattern.html) : The annotated String must match the following regular expression. The regular expression follows the Java regular expression conventions see Pattern. Accepts String. **null elements are considered valid.** – JB Nizet Aug 25 '11 at 11:16
0
if (text != null && !text.matches("\\d{10}")) {
    // not a valid number
}

But since you just tols that you wanted to use the @Pattern annotation to validate a field, then the reqex is sufficient, since, as the javadoc says:

The annotated String must match the following regular expression. The regular expression follows the Java regular expression conventions see Pattern. Accepts String. null elements are considered valid.

(emphasis mine)

So, just use @Pattern("\\d{10}").

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I tried it adding the regular expression -@Pattern("\\d{10}") , but then it still doesn't allows null, only checks for 10digits – user421607 Aug 25 '11 at 11:26
  • Is your string null (s == null), or empty (s.length() == 0), or blank (s.trim().length() == 0)? Those are not the same thing. – JB Nizet Aug 25 '11 at 11:36
-1
[0-9]{10}

If you have any more specific rules, please add them :)