admin管理员组

文章数量:1201581

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?

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?

Share Improve this question asked Apr 10, 2013 at 23:55 Lethal Left EyeLethal Left Eye 3782 gold badges9 silver badges18 bronze badges 1
  • 3 please search before asking. – sachleen Commented Apr 10, 2013 at 23:58
Add a comment  | 

6 Answers 6

Reset to default 8

You need to use ancors, i.e.

/^\d{10}$/

You need to anchor the start and the end too

/^\d{10}$/

This matches 10 digits and nothing else.

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|$)

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/

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}$/)  ;

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');
    }

本文标签: JavaScript Validate Phone Number Using RegexStack Overflow