简体   繁体   中英

JavaScript Validate Phone Number Using Regex

Greetings overflowers,

I'm trying to write a regular expression to validate phone numbers of the form ########## (10 digits) ie 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?

你需要使用ancors ,即

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM