繁体   English   中英

在php jquery中将手机号码验证为10位数字

[英]Validate mobile number into 10 digit numbers in php jquery

我试图验证电话号码时按字母jquery以显示错误消息。 下面的代码需要输入数字,但不能验证到10位数字。 如何验证10位数字。

<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;
                    }
                }
            });
 });

你可以试试这个

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

或者试试这个

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

这是为您提供的工作代码,它可以精确检查10位数字,只接受数字,不能接受其他任何内容:

 $(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' /> 

你可以用这个

 $(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' /> 

只需使用此jquery函数,并在html代码中仅限制十位数字即可

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

并在jquery函数下面使用

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

只需使用此...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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