Thursday, June 30, 2011

Regular expression for validating US phone number

US phone number format validation using regular expression.


The common US phone number format is 3digits-3digits-4digits
eg: 222-333-3333
      111-222-1234
The regular expression for validating this format is

function usphone($string) {
   if(preg_match('/^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$/', $string)) {
    return true;
  }
  else{
    return false;
  }
}

Validation using Javascript

function isUSphone(phoneno) {
   var filter = /^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$/;
   if (filter.test(phoneno))
        returntrue;
    else
        return false; 
}

In Jquery

if($("#phone-num").val().match(/^[0-9]{3}\-[0-9]{3}\-[0-9]{4}$/)) {
  //valid phone number
}
else {
  //not a valid number
}

*phone-num -  id of phone number field(input field)

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Maintained by Web Themes