JavaScript - 仅在范围内验证数字 [英] JavaScript - validate numeric only and within range
本文介绍了JavaScript - 仅在范围内验证数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含许多字段的asp表单。在提交时,我想检查,使用javascript选择了一个复选框,并且在给定范围内的金额字段仅包含数字。我很难让它一次性检查所有三个 - 在mometn我有以下内容:
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:
<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.
任何想法都赞赏。
推荐答案
创建一个可以执行此操作的功能:
Create a function that can do this:
function validate(str, chk, min, max) {
n = parseFloat(str);
return (chk && !isNaN(n) && n >= min && n <= max);
}
然后如下调用:
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;
}
}
这篇关于JavaScript - 仅在范围内验证数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文