Javascript/Jquery:使用数字范围验证输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11121227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript/Jquery: validate input with a number range
提问by Mich Dart
I'd like to validate an input field within a preconfigured range of numbers. Only numbers from 1 up to 24 are allowed.
我想验证预先配置的数字范围内的输入字段。只允许从 1 到 24 的数字。
How can I do?
我能怎么做?
With a custom solution like this:
使用这样的自定义解决方案:
$('.field').keypress(function(event) {
var val = parseInt($(this).val()) + HERE_I_SHOULD_SUM_THE_NEWLY_ADDED_DIGIT;
if(val < 1 || val > 24) event.preventDefault();
});
I'm able to retrieve the current input value. How can I add the newly added digit?
我能够检索当前的输入值。如何添加新添加的数字?
回答by VisioN
How about something like this?
这样的事情怎么样?
?$("input").on("change", function() {
var val = Math.abs(parseInt(this.value, 10) || 1);
this.value = val > 25 ? 24 : val;
});?????????????
回答by Christoph
There are builtin functionalities for inputs in modern browsers:
现代浏览器中有用于输入的内置功能:
A comprehensive overview can be found here: http://www.the-art-of-web.com/html/html5-form-validation/
可以在此处找到全面的概述:http: //www.the-art-of-web.com/html/html5-form-validation/
Basically, you could write:
基本上,你可以写:
<input type="number" min="1" max="24" step="1" required>
with pattern you can define regular expressions to test against:
使用模式,您可以定义正则表达式来测试:
pattern="\d[0-3]"
回答by Alex W
There's a plugin for JQuery that can help you with validation called Valid8:
有一个 JQuery 插件可以帮助您进行名为 Valid8 的验证:
http://unwrongest.com/projects/valid8/
http://unwrongest.com/projects/valid8/
You will need to use a regular expression such as this one:
您将需要使用正则表达式,例如:
^([1-9]|[1]?[1-9]?|[2][0-4]|10)$
回答by Ben McCormick
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x <1|| x >24)
{
alert("Value must be between 1 & 24");
return false;
}
}
Something along those lines should work
沿着这些路线的东西应该工作
回答by Clyde Lobo
Try this
尝试这个
function validate() {
var x = parseInt(value,10) // its the value from the input box;
if(isNaN(x)||x<1||x>24)
{
alert("Value must be between 1 and 24");
return false;
}
}