Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Validate US Phone Number with Regular Expression and Javascript

Posted on 2010-01-12
6
Medium Priority
?
3,952 Views
Last Modified: 2013-12-12
Hi Experts-

I have a contact form that I am validating with jquery validation. Everything works fine except the phone number validation. Onblur I convert the phone number to the following. xxx-xxx-xxxx.

I can't seem to find the regular expression to work in this code that will validate the phone number in this format. It is only validating that is is numeric.

Thanks for your help.
Validation Code:

(function($) {
	$.fn.validationEngine = function(settings) {

	if($.validationEngineLanguage){				// IS THERE A LANGUAGE LOCALISATION ?
		allRules = $.validationEngineLanguage.allRules
	}else{
		allRules = 	{"required":{    			// Add your regex rules here, you can take telephone as an example
						"regex":"none",
						"alertText":"* This field is required",
						"alertTextCheckboxMultiple":"* Please select an option",
						"alertTextCheckboxe":"* This checkbox is required"},
					"length":{
						"regex":"none",
						"alertText":"*Between ",
						"alertText2":" and ",
						"alertText3": " characters allowed"},
					"maxCheckbox":{
						"regex":"none",
						"alertText":"* Checks allowed Exceeded"},	
					"minCheckbox":{
						"regex":"none",
						"alertText":"* Please select ",
						"alertText2":" options"},	
					"confirm":{
						"regex":"none",
						"alertText":"* Your field is not matching"},		
					"telephone":{
						"regex":"/^[0-9-()]+$/",
						"alertText":"* Invalid phone number"},	
					"email":{
						"regex":"/^[\.a-z0-9_\-]+[@][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}$/i",
						"alertText":"* Invalid email address"},	
					"date":{
                         "regex":"/^[0-9]{4}\-\[0-9]{1,2}\-\[0-9]{1,2}$/",
                         "alertText":"* Invalid date, must be in YYYY-MM-DD format"},
					"onlyNumber":{
						"regex":"/^[0-9\ ]+$/",
						"alertText":"* Numbers only"},	
					"noSpecialCaracters":{
						"regex":"/^[0-9a-zA-Z]+$/",
						"alertText":"* No special caracters allowed"},	
					"ajaxUser":{
						"file":"validateUser.php",
						"alertTextOk":"* This user is available",	
						"alertTextLoad":"* Loading, please wait",
						"alertText":"* This user is already taken"},	
					"ajaxName":{
						"file":"validateUser.php",
						"alertText":"* This name is already taken",
						"alertTextOk":"* This name is available",	
						"alertTextLoad":"* Loading, please wait"},		
					"onlyLetter":{
						"regex":"/^[a-zA-Z\ \']+$/",
						"alertText":"* Letters only"}
					}	
	}


Code to convert phone number to xxx-xxx-xxxx

function getLabelForId(id) {
    var label, labels = document.getElementsByTagName('label');
    for (var i = 0; (label = labels[i]); i++) {
        if (label.htmlFor == id) {
            return label;
        }
    }
    return false;
}

function checkPhone() {  
 var phone = document.getElementById('phone');  
 var label = getLabelForId('phone');  
 var digits = phone.value.replace(/[^0-9]/ig, '');  
 if (!digits) {  
   return;  
 }  
 if (digits.length == 10) {  
   phone.value = digits.substring(0, 3) + '-' +    
     digits.substring(3, 6) + '-' +    
     digits.substring(6, 10);  
 } else {  
   phone.value = digits;  
 }  
}

Open in new window

0
Comment
Question by:danjen
  • 3
  • 2
6 Comments
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 26295583
Here is what I would do... Skip the JS validation and just validate it in the action script.  You MUST validate it on the server side anyway, and your clients will almost always know and type their phone numbers correctly.  Here is my function to handle the validation and return a normalized and usually valid phone number.
<?php 
// A FUNCTION TO VALIDATE A PHONE NUMBER AND RETURN A NORMALIZED STRING
// MAN PAGE: http://discuss.fogcreek.com/joelonsoftware3/default.asp?cmd=show&ixPost=102667&ixReplies=15
function strtophone($phone, $format=FALSE, $dlm='-')
{
    // HANDLE INPUT LIKE 1-800-BIG-DOGS
    $phone = strtoupper($phone);
    if (preg_match('/[A-Z]/', $phone))
    {
        $phone = str_replace('A', '2', $phone);
        $phone = str_replace('B', '2', $phone);
        $phone = str_replace('C', '2', $phone);

        $phone = str_replace('D', '3', $phone);
        $phone = str_replace('E', '3', $phone);
        $phone = str_replace('F', '3', $phone);

        $phone = str_replace('G', '4', $phone);
        $phone = str_replace('H', '4', $phone);
        $phone = str_replace('I', '4', $phone);

        $phone = str_replace('J', '5', $phone);
        $phone = str_replace('K', '5', $phone);
        $phone = str_replace('L', '5', $phone);

        $phone = str_replace('M', '6', $phone);
        $phone = str_replace('N', '6', $phone);
        $phone = str_replace('O', '6', $phone);

        $phone = str_replace('P', '7', $phone);
        $phone = str_replace('Q', '7', $phone);
        $phone = str_replace('R', '7', $phone);
        $phone = str_replace('S', '7', $phone);

        $phone = str_replace('T', '8', $phone);
        $phone = str_replace('U', '8', $phone);
        $phone = str_replace('V', '8', $phone);

        $phone = str_replace('W', '9', $phone);
        $phone = str_replace('X', '9', $phone);
        $phone = str_replace('Y', '9', $phone);
        $phone = str_replace('Z', '9', $phone);
    }

    // DISCARD NON-NUMERIC CHARACTERS
    $phone = preg_replace('/[^0-9]/', '', $phone);

    // DISCARD A LEADING '1' FROM NUMBERS ENTERED LIKE 1-800-555-1212
    if (substr($phone,0,1) == '1') $phone = substr($phone,1);

    // IF LESS THAN TEN DIGITS, IT IS INVALID
    if (strlen($phone) < 10) return FALSE;

    // IF IT STARTS WITH '0' OR '1' IT IS INVALID, SECOND DIGIT CANNOT BE '9' (YET)
    if (substr($phone,0,1) == '0') return FALSE;
    if (substr($phone,0,1) == '1') return FALSE;
    if (substr($phone,1,1) == '9') return FALSE;

    // ISOLATE THE COMPONENTS OF THE PHONE NUMBER
    $ac = substr($phone,0,3); // AREA
    $ex = substr($phone,3,3); // EXCHANGE
    $nm = substr($phone,6,4); // NUMBER
    $xt = substr($phone,10);  // EXTENSION

    // ADD OTHER TESTS HERE AS MAY BE NEEDED - THESE ARE OFTEN CONSIDERED INVALID 
    if ($ac == '900') return FALSE;
    if ($ac == '976') return FALSE;
    if ($ex == '555') return FALSE;

    // IF NOT FORMATTED
    if (!$format) return $phone;

    // STANDARDIZE THE PRINTABLE FORMAT OF THE PHONE NUMBER LIKE 212-555-1212-1234
    $formatted_phone = $ac . $dlm . $ex . $dlm . $nm;
    if ($xt != '') $formatted_phone .= $dlm . $xt;
    return $formatted_phone;
}

Open in new window

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 26295769
Bookmark this site: http://regexlib.com/

Search for "us phone number"

Look for a highly rated expression, e.g., the one by "kode kode"

^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$

You can even test it out on one of the RegExp test pages, e.g.,
http://regexpal.com/
0
 

Author Comment

by:danjen
ID: 26295915
Thank you - I have used the site you mentioned and have tried inserting this into the code, but it creates problems on the form validation if i change the telephone validation to this.

"telephone":{
                                    "regex":"/^\(?[\d]{3}\)?[\s-]?[\d]{3}[\s-]?[\d]{4}$/",
                                    "alertText":"* Invalid phone number"},      

It causes the validation to stop here.

Ray - On the script that you posted what would I put in my form input to call this validation and how do I display an error if it fails?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26296564
Hi, danjen.  This would go in the action script - that is the script that processes the form input on the server side.  A sample calling sequence would be like this...

In this example, we assume that your data is submitted via method=post, and that the name of the <input> field in the <form> is "phone" - please change this to match your application needs if necessary.
// INTERPRET THE PHONE
$my_phone = strtophone($_POST["phone"]);

// IF FUNCTION strtophone() RETURNS FALSE, IT IS A BOGUS PHONE NBR
if (!$my_phone) echo "ERROR IN PHONE";

Open in new window

0
 

Author Closing Comment

by:danjen
ID: 31676242
Thanks for your help Ray!
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 26304572
You're welcome, and thanks for the points, ~Ray
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

569 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question