Avatar of wintersun
wintersun
Flag for Singapore asked on

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!
Regular Expressions

Avatar of undefined
Last Comment
wintersun

8/22/2022 - Mon
kaufmed

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

Open in new window

wintersun

ASKER
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.
kaufmed

Remove the backslashes before each curly brace. I didn't not put those in my pattern for a reason  ; )
Your help has saved me hundreds of hours of internet surfing.
fblack61
wintersun

ASKER
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.
kaufmed

Take the star out. Also, I need to ammend the pattern slightly:

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

Open in new window

wintersun

ASKER
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?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
kaufmed

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
wintersun

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

Above is working in my case after testing.

Thanks.