1

I am struggling with getting the right regex for a phone number validation in my application. I have got a regex that will accept only numbers and some special symbols like ()- etc, however, the problem is that it accepts only symbols as well. So for example, it would accept something like ()()()(). I want to modify the regex or get a whole new regex that accepts these symbols but it should have at least one number before and after each symbol.

My requirements are:

  1. Only numbers
  2. Number with combination of special symbols
  3. Each symbol should be followed by a number (before and after) but white spaces are okay
  4. Max length should be 15
3
  • 2
    There are valid phone numbers longer than 15 digits, particularly international ones. And what about extensions (... x123)? Commented Oct 20, 2011 at 21:21
  • No, I don't want to handle extension. And valid length is only 15 for my application. I am using this regex currently. ^ *[0-9()- ]*$ , how can I make number mandatory in here. Currently, the only special symbols supported are ()-. Commented Oct 20, 2011 at 21:44
  • Fair enough. I'm not suggesting you should handle international phone numbers in all their generality, just that you should be explicitly aware of what restrictions you're imposing. Out of curiosity, where does the number 15 come from? (US phone numbers are at most 10 digits, 11 if you count the leading 1.) Commented Oct 20, 2011 at 22:43

1 Answer 1

1

In my experience, the parenthesis only appear around the first group of digits and there are never fewer than 3 digits in a group. This regex does that, and prevents multiple consecutive separators with the exception of a space following a paren "(123) 456-7890". I also added support for periods as separators. It allows for 1, 2, or 3 groups of numbers and attempts to enforce an overall range of 7-15 digits but it errs on the permissive side.

^\\s*(\\d{7,15})||(\\d{3,12}[\\-.]?\\s?\\d{3,12}[\\-.\\s]?)||([(]?\\d{3,9}[)\\-.]?\\s?\\d{3,9}[\\-.\\s]?\\d{3,9})\\s*

In my environment I have to escape the backslashes - you may not have to so you may need to replace the \ with . The hyphen must be escaped because in this context it represents a range.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you all. The combination of above responses should help me. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.