[英]Javascript/JQuery how to validate phone number
如何驗證輸入字段以輸入手機號碼,該手機號碼也應以“ 07”開頭,如果有人用空格輸入手機號碼,則單擊時應刪除空格。 。 例如:07 xxxx xxxx onclick,應為07xxxxxxxx
現在,我使用html 5驗證方法發出警告:
<input type="text" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" pattern="\d{10}">
但是此代碼無法對其進行驗證。 有人可以幫我驗證一下嗎
當我必須解決相同的問題時,我使用了Masked Input Plugin。
您要求我使用簡單的javascript進行操作。
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction()
{
var xyz=document.getElementById('mob_no').value.trim();
if(xyz.substr(0,2)==='07')
{
var new_no= document.getElementById('mob_no').value.replace(/\s/g,"")
alert("number after validations check is"+new_no);
}
else
{
alert("incorrect number");
}
}
<input type="text" id="mob_no" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" onblur="myFunction()">
</body>
</html>
隨時提出任何問題,請回復是否有效。
您以07開頭的電話號碼的接受方式是
<input type="text" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" pattern="^07\d{8}$">
首先驗證07
,然后再接受以下8位數字,如下所示
pattern="^07\d{8}$"
尼爾斯有正確的想法。
因此,只需附加一個單擊處理程序或刪除空格的行為即可。
var a = "07989 8989 8 8";
//substitute your element reference ala jQuery('input[name="mobile_number"]');
a = a.replace(/\s+/g,''); // strip the white space
if( /^07\d{8}$/.test(a) ){
// passed test
}else{
// did not pass, show error
}
我相信,就像Niles所說的那樣,您將希望使用模式pattern="^07\\d{8}$"
,這意味着,在英語String starting with "07" ending with any numerical sequence equaling 8 characters
此外,就像James指出的那樣,請使用Javascript刪除空格。 但是,我將添加一個間隔,以自動清除它們,以便用戶了解輸入的工作方式以進一步使用。
<script type="text/javascript">
var inputElm = document.getElementById('phone_number_id_name'), // id="" name of element
input = inputElm.value;
setInterval(function() { inputElm.value = input.replace(/\s+/g, ''); }, 100); // turncate white-space of input every 100ms
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.