[英]Min Max validation with javascript
我有以下输入:
<input type="number" class="form-control custom-values" name="Width" id="item-b" min="1201" max="1500" value="1361">
我正在尝试确保用户输入的值在最小最大边界内。 但是,我遇到了一个奇怪的问题。
当我使用此脚本检查值时:
if($(this).val() > $(this).attr("max") || $(this).val() < $(this).attr("min")){
alert("out of bounds");
all_custom_sizes_valid = false;
}else if($(this).val() < $(this).attr("max") || $(this).val() > $(this).attr("min")){
if(!all_custom_sizes_valid){
alert("fixed to in bounds");
all_custom_sizes_valid = true;
}else{
alert("in bounds");
}
}
一切正常。
但是,当我在输入框中输入150时,它会提醒我该值在范围内。 150是我能够找到的唯一执行此操作的号码。
我还遇到其他问题,当我更改回有效值并且没有弹出“固定在范围内”警报时,验证无法正确更新。
任何见识将不胜感激。
您正在比较字符串。 $(this).val()
和$(this).attr("max")
都是字符串(与min
属性的值一样)。
以这种方式查看测试,这两个都是正确的: "150" > "1201"
和"150" < "1500"
(可以在浏览器控制台中尝试)。 您可以使用parseInt()
获得可以比较的整数值。
另一个问题是您应该使用&&而不是|| 比较之间(您希望它大于min 并且小于max)。
如果您首先将值放入变量,它也会看起来更好(至少对我来说是这样)),您也可以应用int转换: var currentValue = parseInt($(this).val())
等。
现在,您所有的比较都是字符串,而不是数字。 尝试在比较之前使用parseInt或类似操作将每个值转换为数字
您的else if语句不应使用||
。
它应该是
else if($(this).val() < $(this).attr("max") && $(this).val() > $(this).attr("min")){
我认为150次通过的原因是因为这条线
if($(this).val() < $(this).attr("max") || $(this).val() > $(this).attr("min")){
由于OR运算符,它会泄漏。 '如果150是<1500或150> 1200',那就做...
Javascript认为第一个条件已满足,因此继续进入if循环。 用AND'&&'运算符替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.