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!
wintersunAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
käµfm³d 👽Connect With a Mentor 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
 
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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
käµfm³d 👽Commented:
Remove the backslashes before each curly brace. I didn't not put those in my pattern for a reason  ; )
0
 
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
 
wintersunAuthor Commented:
private static final Pattern phonePattern = Pattern.compile("[\\d-()+\\s]{6,15}");

Above is working in my case after testing.

Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.