JavaScript - 仅验证数字且在范围内
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12063070/
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 - validate numeric only and within range
提问by grn_uk
I have an asp form which has a number of fields. On submit I want to check, using javascript that a tickbox has been selected and that an 'amount' field in within a given range AND has numbers only. I'm struggling to get it to check all three in one go - at the mometn i have the following:
我有一个包含多个字段的 asp 表单。在提交时,我想使用 javascript 检查是否已选择了一个复选框,并且在给定范围内的“金额”字段只有数字。我正在努力让它一次性检查所有三个 - 目前我有以下几点:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if (x<5 || x >250)
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
At the moment this is two seperate checks for tick box select and range.
目前,这是对复选框选择和范围的两个单独检查。
Any ideas appreciated.
任何想法表示赞赏。
回答by Mohamed Nuur
Create a function that can do this:
创建一个可以执行此操作的函数:
function validate(str, chk, min, max) {
n = parseFloat(str);
return (chk && !isNaN(n) && n >= min && n <= max);
}
then call it like so:
然后像这样调用它:
function validateForm()
{
if(!validate(document.forms["myForm"]["Amount"].value,
document.forms["myForm"]["agreesubmit"].checked, 5, 250)) {
alert("Please complete all required fields - Amount you wish to save");
return false;
}
}
回答by Jared Drake
Try using the isNan(). Tutorial found at http://www.w3schools.com/jsref/jsref_isnan.asp
尝试使用 isNan()。教程位于http://www.w3schools.com/jsref/jsref_isnan.asp
Something like:
就像是:
if (isNaN(x) || x < 5 || x > 250))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
Quick note you might be confused about the or/ands, so notice that the x<5 || x >250 is wrapped in () so that it can be partnered with the and numeric condition. Then, finally the whole if wraps the statements.
快速说明您可能对 or/ands 感到困惑,因此请注意 x<5 || x >250 包含在 () 中,以便它可以与数字条件配合使用。然后,最后整个 if 包装了语句。
回答by T.W.R. Cole
This will ensure it has numbers only first, then check the number against a range.
这将确保它首先只有数字,然后根据范围检查数字。
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if( String(x).search(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/) != -1
&&( x<5 || x >250 ))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>