Tuesday, May 15, 2012

Validate phone numbers using jQuery

Now days registration forms have phone numbers as mandatory field. But how to validate the entered phone number is correct or not? In this post, I will show you how to validate the phone number using jQuery. To validate the phone number, I have created a function which based on input, returns true or false. It checks for the validity of phone number using regular expression.
//Code Starts
function validatePhone(txtPhone) {
    var a = document.getElementById(txtPhone).value;
    var filter = /^[0-9-+]+$/;
    if (filter.test(a)) {
        return true;
    }
    else {
        return false;
    }
}​
//Code Ends
The above regular expression allows only numerals and + or – signs. Based on your requirement you can modify this regular expression.

Now call this function to validate the phone number. For demo, I have used on blur event of textbox But It can be used on click on button or any another event. Based on the result, it updates the status in a span tag.
//Code Starts
$('#txtPhone').blur(function(e) {
   if (validatePhone('txtPhone')) {
       $('#spnPhoneStatus').html('Valid');
       $('#spnPhoneStatus').css('color', 'green');
   }
   else {
      $('#spnPhoneStatus').html('Invalid');
      $('#spnPhoneStatus').css('color', 'red');
   }
});
//Code Ends
See result below.



Feel free to contact me for any help related to jQuery, I will gladly help you.