3

Greetings overflowers,

I'm trying to write a regular expression to validate phone numbers of the form ########## (10 digits) i.e. this is these are cases that would be valid: 1231231234 or 1111111111. Invalid cases would be strings of digits that are less than 10 digits or more than 10 digits.

The expression that I have so far is this: "\d{10}"

Unfortunately, it does not properly validate if the string is 11+ digits long.

Does anyone know of an expression to achieve this task?

1

6 Answers 6

8

You need to use ancors, i.e.

/^\d{10}$/
0
4

You need to anchor the start and the end too

/^\d{10}$/

This matches 10 digits and nothing else.

0
3

This expression work for google form 10 digit phone number like below:

(123) 123 1234 or 123-123-1234 or 123123124

(\W|^)[(]{0,1}\d{3}[)]{0,1}[\s-]{0,1}\d{3}[\s-]{0,1}\d{4}(\W|$)
2

I included the option to use dashes (xxx-xxx-xxxx) for a better user experience (assuming this is your site):

var regex = /^\d{3}-?\d{3}-?\d{4}$/g
window.alert(regex.test('1234567890'));

http://jsfiddle.net/bh4ux/279/

3
  • Simpler to remove dashes (and probably spaces too if you're going to be accommodating) and use a simple /^\d{10}$/ expression.
    – RobG
    Commented Apr 11, 2013 at 1:43
  • @RobG I have done lots of validation for major websites and I was merely mentioning the fact that users get frustrated if they cannot enter dashes. The regex you mentioned doesn't allow dashes at all.
    – Alex W
    Commented Apr 11, 2013 at 2:07
  • 1
    —I was suggesting that dashes and spaces be removed before testing, e.g. re.test(s.replace(/[\s-]/g)), rather than not allowing them to be used.
    – RobG
    Commented Apr 11, 2013 at 3:27
1

I usually use

phone_number.match(/^[\(\)\s\-\+\d]{10,17}$/)

To be able to accept phone numbers in formats 12345678, 1234-5678, +12 345-678-93 or (61) 8383-3939 there's no real convention for people entering phone numbers around the world. Hence if you don't have to validate phone numbers per country, this should mostly work. The limit of 17 is there to stop people from entering two many useless hyphens and characters.

In addition to that, you could remove all white-space, hyphens and plus and count the characters to make sure it's 10 or more.

var pureNumber = phone_number.replace(/\D/g, "");

A complete solution is a combination of the two

var pureNumber = phone_number.replace(/\D/g, "");
var isValid = pureNumber.length >= 10 && phone_number.match(/^[\(\)\s\-\+\d]{10,17}$/)  ;
0

Or this (which will remove non-digit characters from the string)

var phoneNumber = "(07) 1234-5678";
phoneNumber = phoneNumber.replace(/\D/g,'');
if (phoneNumber.length == 10) {
    alert(phoneNumber + ' contains 10 digits');
    }
else {
    alert(phoneNumber + ' does not contain 10 digits');
    }

Not the answer you're looking for? Browse other questions tagged or ask your own question.