-2

Am using jQuery to validate my form. How can I create a custom phone validation regular expression so that I can validate my phone field to accept numbers with hyphen and not in any particular order it may be 33333-23232, or 343-3434-343434, or in any form but it must have only numeric and hyphen.

I have tested with this var intRegex = /^[2-9]\d{2}-\d{3}-\d{4}$/; but this is will be for a particular order like 999-999-9999.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
Ranjani
  • 153
  • 1
  • 3
  • 12
  • 1
    This has nothing to do with jQuery. It's a simple JavaScript problem. jQuery may be popular, but people need to learn that it's a library that adds functionality on top of JavaScript. A JavaScript problem often doesn't require jQuery. – Dan Dascalescu Feb 26 '14 at 07:22
  • Second, you shouldn't use regular expressions to [validate phone numbers properly](http://stackoverflow.com/a/4338544/1269037). – Dan Dascalescu Feb 26 '14 at 07:53

2 Answers2

1

One regular expression is /^[\d-]+$/, but you should learn more about regular expressions and play with some data in a playground like http://regex101.com.

Anyway, using a simple regular expression to validate phone numbers is naive. The following are phone numbers that users will want to be able to enter:

+1-415.123.4567

+1-408-123-MARC

(650)-123-4567

And that's U.S. alone.

There are entire articles on validating phone numbers with regular expressions and comprehensive StackOverflow questions. Don't use regular expressions. Use a specialized library like Google's liphonenumber.

Community
  • 1
  • 1
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
  • It does allow digits and the hyphen. As advised, test it at http://regex101.com/r/hE7kV0 – Dan Dascalescu Feb 26 '14 at 07:41
  • yes it (var intRegex =/^[\d-]+$/;) allows these types of format 1.only numbers 2.only numbers and hyphen .Any way to allow format 2 alone? – Ranjani Feb 26 '14 at 08:28
-1

Used var intRegex =/^[\d-]+$/; to check if it is only with numbers or numbers and hyphen in no particular order

Ranjani
  • 153
  • 1
  • 3
  • 12
  • 1
    The `|` in the middle of the `[]` character class doesn't do what you think :) That regexp will also match "123-456|7890". Again, my answer is correct. – Dan Dascalescu Feb 26 '14 at 08:45