• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 371
  • Last Modified:

Urgent: Phone Number Regular Expression Validation

I need a regular expression to limit digits for phone number fields to no more than 15 digits and also allow the special characters listed below:-

-
()
+

Can someone show me how to do it in regular expressions?

Thanks & Happy New Year!
0
wintersun
Asked:
wintersun
  • 4
  • 4
1 Solution
 
käµfm³d 👽Commented:
String pattern = "[\\d-0+]{,15}";

Open in new window

0
 
wintersunAuthor Commented:
I try to test it on my Java application with the code below:-

private static final Pattern phonePattern = Pattern.compile("[\\d-()+]\\{,15\\}");


However, the input (listed below) failed to pass the pattern.

56100
07-5767880
713-434-7798
+6423412555

Please advise.
0
 
käµfm³d 👽Commented:
Remove the backslashes before each curly brace. I didn't not put those in my pattern for a reason  ; )
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
wintersunAuthor Commented:
If I remove the backslashes before each curly brace, the following runtime error will be appeared:-


java.util.regex.PatternSyntaxException: Illegal repetition near index 10
[\d-()+\s]*{,15}

Any thoughts?
Thanks.
0
 
käµfm³d 👽Commented:
Take the star out. Also, I need to ammend the pattern slightly:

String pattern = "[\\d()+-]{,15}";

Open in new window

0
 
wintersunAuthor Commented:
Still having the same error returned:-

java.util.regex.PatternSyntaxException: Illegal repetition near index 7
[\d()+-]{,15}
       ^
      at java.util.regex.Pattern.error(Pattern.java:1924)
      at java.util.regex.Pattern.closure(Pattern.java:3104)
      at java.util.regex.Pattern.sequence(Pattern.java:2101)
      at java.util.regex.Pattern.expr(Pattern.java:1964)
      at java.util.regex.Pattern.compile(Pattern.java:1665)
      at java.util.regex.Pattern.<init>(Pattern.java:1337)
      at java.util.regex.Pattern.compile(Pattern.java:1022)

What do you think?
0
 
käµfm³d 👽Commented:
You might need to explicitly declare the zero:

String pattern = "[\\d()+-]{0,15}";

Open in new window


Or use a 1 if you need at least one item.
0
 
wintersunAuthor Commented:
private static final Pattern phonePattern = Pattern.compile("[\\d-()+\\s]{6,15}");

Above is working in my case after testing.

Thanks.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now