【问题标题】:jQuery set min and max value for phone number with validationjQuery通过验证设置电话号码的最小值和最大值
【发布时间】:2019-01-20 19:31:07
【问题描述】:

我需要验证我的input type="text",当按键时最小值为 7,最大值为 13。我还需要验证是否只输入数字。我尝试了一些参考堆栈,但未能解决。任何人都可以帮助我实现这一目标。

$("#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>

【问题讨论】:

  • 您是否要验证电话号码,最少 7 位,最多 13 位。
  • @iNullPointer 是的。
  • 检查我的答案。
  • @iNullPointer 可以根据我的问题发送示例链接并带有警报消息。

标签: javascript jquery html css validation


【解决方案1】:

你应该使用正则表达式来验证它

验证数字的函数

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

如果数字有效(即,它仅包含数字 0 to 9 和最小 7 digits 和最大 13 digits long),此函数将返回 true,否则返回 false。

【讨论】:

  • 您能否添加示例链接和示例警报消息
  • @Sharvan jsFiddle
  • @Sharvan 希望这会对您有所帮助。
  • 当我输入字符时开始输入需要提醒只输入数字。
  • @Sharvan 我已经更新了我的答案。希望它能解决您的问题。
猜你喜欢
  • 2011-03-21
  • 2019-02-09
  • 2022-07-06
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 2022-12-01
相关资源
最近更新 更多