繁体   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