phone number validation in jQuery-javascript?


 How can i validate phone number using jquery-javascript? Suppose, i want to validate phone number for this textbox

<input type="text" class="phone-number form-control" id="phone-number"  />

thanks


Asked by:- Vipin
1
: 3461 At:- 6/21/2017 1:27:17 PM
jquery javascript phone-number validation






1 Answers
profileImage Answered by:- vikas_jk

Hello, there are several ways to validate your textbox for phone numbers:

  • Using jQuery plugins like
    -> jQuery Validate PhoneUS Method

    $( "#myform" ).validate({
      rules: {
        phone-number: {
          required: true,
          phoneUS: true
        }
      }
    });

    For using above Validation method, you need to add this script reference with jQuery validate "https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"

  •  Using Custom JS Method
    function validatePhone(txtPhone) {
        var a = document.getElementById(txtPhone).value;
        var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
        if (filter.test(a)) {
            return true;
        }
        else {
            return false;
        }
    }


  • Using method to allow only numbers like
    //it will only allow numeric keys
     $(".AllowNumeric").on("keypress keyup blur",function (event) {    
               $(this).val($(this).val().replace(/[^\d].+/, ""));
                if ((event.which < 48 || event.which > 57)) {
                    event.preventDefault();
                }
            });
    
  • UK Phone number validation script

          var reg =  /^((\+44\s?|0)7([45789]\d{2}|624)\s?\d{3}\s?\d{3})$/ ; //UK phone regex 
          function PhoneValidation(phoneNumber)
          {  
           
            var OK = reg.exec(phoneNumber);  
            if (!OK)  
              window.alert("phone number isn't  valid");  
            else  
              window.alert("phone number is  valid");  
          }  
    


    Fiddle: https://jsfiddle.net/85n1yato/ (Try checking sample number: +447440965338)

Regex Phone number validation for US phone Number

      var reg = /\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/; //US regex
      function PhoneValidation(phoneNumber)
      {  
      
        var OK = reg.exec(phoneNumber);  
        if (!OK)  
          window.alert("phone number isn't  valid");  
        else  
          window.alert("phone number is  valid");  
      }  

Sample fiddle: https://jsfiddle.net/87hfg201/

0
At:- 6/21/2017 1:54:53 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use