jQuery Phone Number Validation Example

In this post, I explain jQuery phone number validation using regex. Mobile number validation in jQuery is need when you get validate phone number.

We will easy to explain 10 digit phone number validation in jQuery using regular expression pattern. Regex through you can get valid mobile number.

<!DOCTYPE html>
<html>
  <head>
      <title>How to phone number validation in jQuery</title>
</head>
<body>
    
    <form action="">
        <label for="phone">Phone</label>
        <input type="text" name="phone" id="phone" placeholder="Enter phone" maxlength="10">
        <span id="phoneError"></span>
        <br><br>
        <input type="button" value="Submit" id="submitForm">
    </form>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>  
    $(document).ready(function() {
      $('#submitForm').click(function(){
        var phone = $('#phone').val();
        var phoneNum = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

        if(phone == ""){
            $("#phoneError").text("Please enter phone").css("color","red");
        }else if(!phone.match(phoneNum) || phone.length != 10){
            $("#phoneError").text("Please enter valid phone").css("color","red");
        }else{
            $("#phoneError").text("Phone number is valid").css("color","green");
        }
      });

      $("#phone").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                $("#phoneError").html("Enter only digits").css('color','red');
                return false;
            }
        });
    });
</script>
</body>
</html>

I hope you understand jQuery phone number validation..