[英]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.