简体   繁体   中英

Validate mobile number into 10 digit numbers in php jquery

I am trying to validate phone number jquery when alphabets are pressed it as to display error message. Below code takes enters digits but doesnt validate to 10 digits. How to validate to 10 digit number.

<script type="text/javascript" >
 $(function() {
   $("#phno").bind("keypress", function (event) {
                if (event.charCode != 0) {
                       var regex = new RegExp("^[0-9]{10}$");
                    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                    if (!regex.test(key)) {
                      alert("Please enter valid Student Phone No");
                        event.preventDefault();
                        return false;
                    }
                }
            });
 });

You can try this

var regex = new RegExp("/^[0-9]{1,10}$/");

Or try this

var str='0123456789';
console.log(str.match(/^\d{10}$/)); // retunr null if don't match

Here is a working code for you which EXACTLY checks for 10 digits, only accepts numbers and nothing else:

 $(function() { $("#phno").bind("keydown", function(event) { var a = $(this).val(); if (a.match(/^\\d{9}$/)) { console.log("Perfect!"); } else { console.log("Invalid. Ensure, there are 10 digits."); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' id='phno' /> 

you can use this

 $(function() { $("#phno").bind("keydown", function (e) { if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) { // 0-9 var val = $(this).val(); if (!val.match(/^\\d{9}$/)) { console.log("it is a number but nut match 10 digit") } else { console.log("success"); return false; // to restrict user to not enter more than 10 digit } } else { if(e.keyCode == 8) return true; // backspace alert("Please enter valid Student Phone No"); event.preventDefault(); return false; } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type='text' id='phno' /> 

Just use this jquery function and restrict only ten digits in your html code as

<input type="text" name="phone" maxlength="10" id="phone"/>

and use this below jquery function

$("#phone").bind("keypress", function (event) {  
    var phoneno = /^\d{10}$/;  
    var phone_val=$('#phone').val();
    if((phoneno.test(phone_val)))
    {
     return true;  
    }  
    else  
    {    
     return false;  
    }  
});

Simply use this...

var num = '1234567890';
if(!isNaN(num) && num.length ==10){ alert('Validated');  }
else { alert('Not a 10 digit number'); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM