簡體   English   中英

jQuery通過驗證設置電話號碼的最小值和最大值

[英]jQuery set min and max value for phone number with validation

當按鍵的最小值為7而最大值為13時,我需要驗證input type="text" 。此外,我還需要驗證僅輸入數字。 我嘗試使用一些參考堆棧,但無法解決。 任何人都可以幫助我實現這一目標。

 $("#phone").bind("keyup keydown", function() { var amount = parseFloat($(this).val()); if (amount) { if (amount > 7 || amount < 13) { $("span.phonealert").html("Your number must be between 7 and 13"); } else if(amount < 13) { $("span.phonealert").html("valid phone number"); } } else { $("span.phonealert").html("Enter numbers only"); } }); 
 #phone { height:40px; width:200px; padding:5px; font-size:15px; } 
 <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <form> <input type="text" name="phone" id="phone" maxlength="13" autocomplete="off" placeholder="eg: 01234567890" value=""/> <span class="phonealert"></span> </form> </body> </html> 

您應該使用正則表達式進行驗證

驗證號碼功能

function verifyPhoneNumber(number){
  var validity = new RegExp("^[0-9]{7,13}$");
  return validity.test(number);
}

檢查和確認按鍵功能

$('#phone').keypress(function(e){
  // 48-57 are code of digits 0-9.
  if (![48, 49, 50, 51, 52, 53, 54, 55, 56, 57].includes(e.keyCode)){
    e.preventDefault();
    alert("Enter digits only.");
  }
});

如果數字有效,則此函數將返回true(即,它僅包含數字0 to 9 ,最小7 digits ,最大13 digits長),否則返回false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM