Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to validate US phone numbers? [duplicate]

Possible Duplicate:
A comprehensive regex for phone number validation
Validate phone number with JavaScript

I'm trying to write a regular expression to validate US phone number of format (123)123-1234 -- true 123-123-1234 -- true

every thing else in not valid.

I came up something like

 ^\(?([0-9]{3}\)?[-]([0-9]{3})[-]([0-9]{4})$ 

But this validates, 123)-123-1234 (123-123-1234

which is NOT RIGHT.

like image 405
Priya Avatar asked Mar 19 '12 19:03

Priya


People also ask

What is the regular expression for phone number?

Regular expression to allow numbers like +111 123 456 789: ^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$

How can I validate a phone number in JavaScript?

Validate a Phone Number Using a JavaScript Regex and HTML function validatePhoneNumber(input_str) { var re = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/; return re. test(input_str); } function validateForm(event) { var phone = document. getElementById('myform_phone').

What is RegEx in validation?

What is RegEx Validation (Regular Expression)? RegEx validation is essentially a syntax check which makes it possible to see whether an email address is spelled correctly, has no spaces, commas, and all the @s, dots and domain extensions are in the right place.


1 Answers

The easiest way to match both

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$ 

and

^[0-9]{3}-[0-9]{3}-[0-9]{4}$ 

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$ 

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$ 

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)

like image 188
ruakh Avatar answered Oct 15 '22 23:10

ruakh