多种形式的jQuery表单验证添加方法 [英] jQuery form-validation addmethod in multiple forms
问题描述
简短说明:具有约30个表格的页面,使用自定义方法通过jQuery验证插件进行验证(将字段1与字段2进行比较,并确保字段2> =字段1).
Short description: Page with ~30 forms, using a custom method to validate with jQuery validation plugin (compares field 1 to field 2 and makes sure field 2 >= field 1).
我基本上有这个问题,除了每页有30种表格,而不仅仅是2种.我想我可以使用class标签来使验证插件获取与验证形式相同的输入-但即使是在验证第二种形式时,它也总是用于第一种形式的输入.
I basically have this problem, except there's 30 forms per page and not just 2. I thought I could use the class tag in order for the validation plugin to grab the input that's in the same form that it's validating - but it always goes for the one that's in the first form, even when validating the second form.
是否有一种方法可以在不为每种表单创建单独的验证脚本的情况下完成这项工作?
Is there a way to make this work without making a separate validation script for every form?
下面的jsfiddle html代码:
The jsfiddle html code below:
<form id='test'>Start :
<select name='start' class='dayStart'>
<option value='1'>1</option>
<option value='1.5'>1.5</option>
<option value='2'>2</option>
</select>
<br />Stop :
<select name='stop' class='dayStop'>
<option value='1'>1</option>
<option value='1.5'>1.5</option>
<option value='2'>2</option>
</select>
<br />
<input type='submit' />
</form>
<form id='test2'>Start :
<select name='start' class='dayStart'>
<option value='1'>1</option>
<option value='1.5'>1.5</option>
<option value='2'>2</option>
</select>
<br />Stop :
<select name='stop' class='dayStop'>
<option value='1'>1</option>
<option value='1.5'>1.5</option>
<option value='2'>2</option>
</select>
<br />
<input type='submit' />
</form>
还有这里的js:
jQuery.validator.addMethod("stop_boet_start", function () {
return (parseFloat($(".dayStop").val()) >= parseFloat($(".dayStart").val()));
}, "* error_msg");
$("#test").validate({
rules: {
stop: {
stop_boet_start: true
}
}
});
$("#test2").validate({
rules: {
stop: {
stop_boet_start: true
}
}
});
推荐答案
为了找到正确的dayStart和dayStop元素,可以使用以下命令:
In order to find the correct dayStart and dayStop elements you can use following:
jQuery.validator.addMethod("stop_boet_start", function (value, element, params) {
var form = $(element).closest("form");
var dayStop = form.find(".dayStop");
var dayStart = form.find(".dayStart");
return (parseFloat(dayStop.val()) >= parseFloat(dayStart.val()));
}, "* error_msg");
$("#test").validate({
rules: {
stop: {
stop_boet_start: true
}
}
});
$("#test2").validate({
rules: {
stop: {
stop_boet_start: true
}
}
});
这篇关于多种形式的jQuery表单验证添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!