开发者

phone number format checking javascript

I have made a website with JS and php and as you can see below is my code at paste bin, I have looked around and seen regular expressions but I don't know how to use them or what I should use exactly....But basically I want to just allow the user to enter north american phone numbers and if they enter anything else then give them a message to enter a valid phone number...

Below is my code to help you understand what I have..What I need and what my site's interface looks like...

http开发者_运维知识库://pastebin.com/8NwURm0G

possible phone numbers user can enter are 9058554678 OR 4167641689...

This is how the the list looks:

http://dev.icalapp.rogersdigitalmedia.com.rogers-test.com/Edit.php


Here is regex that I have laying around to only match 10 digit NA numbers, based off the NANP

/(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})/


It's worth reading up on regular expressions before using them, since they can be a little tricky and unintuitive.

Good tutorial: http://www.regular-expressions.info/quickstart.html

Based on what you list as a valid input, you're looking to see if the user entered in 10 digits. This can be done by checking if a character is a digit, and then seeing if there are 10 of them, which would be the regular expression: [0-9]{10}. Example on how to use:

var myRegEx = /[0-9]{10}/;
var itemsToTest = ["9058554678","abc"];

for (var ii=0;ii<itemsToTest.length;ii++) {
    if ( myRegEx.test(itemsToTest[ii]) ) {
        alert(itemsToTest[ii] + " is valid!");
    }
}

Test: http://jsfiddle.net/87ea8/


^\d{10}$

That matches 10-digit numbers.

^1?\d{10}$

That matches 10-digit numbers with an optional 1 at the front.

^(?:1-?\s*)?(?:\(?:\d{3}\)|\d{3})\s*-?\d{4}$

That matches digit groupings like 1-444-555-6666 or (444) 555-6666, and some related ones.


A quick search on google yielded the following result. You might want to combine it with mitchellhislop's answer.

function isPhoneNumber(s)
{

 // Check for correct phone number
 rePhoneNumber = new RegExp(/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/);

 if (!rePhoneNumber.test(s)) {
      alert("Phone Number Must Be Entered As: (555) 555-1234");
      return false;
 }

return true;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜