有条件的jQuery验证插件规则? [英] jquery validation plugin rules with condition?
问题描述
我正在使用Jquery验证插件,我的表单很大,带有保存",提交"按钮. 我对两个按钮有两组规则.
I am using Jquery validation plugin , I have a big form with "Save","Submit" buttons. I have two sets of rules for two buttons.
- 每当用户单击保存"按钮时,只有有效的规则一组规则(必填字段电子邮件,密码).
- 每当用户单击保存"按钮时,只有有效的规则两组规则(所有必填字段).
任何人都建议,如何这样发展?
Any one suggest please, how to develop like this ?
Set1规则:
var rulesOne = { email : "required" .......}
Set2规则:
var rulesTwo = {city : "required" ..........}
$("#form1").validate({
ignore : '*:not([name]),:hidden',
rules : rules});
如果保存按钮
if(this.id == "personal_save"){
setOne rules test ?
else
// submit button (check all validations)
{
setTwo rules test ?
}
谢谢 普拉萨德
推荐答案
使用此插件无法动态打开/关闭表单的任何/所有部分的验证.
You cannot dynamically turn validation on/off for any/all parts of a form with this plugin.
但是,您可以使用 .rules()
方法动态添加,删除或覆盖您的随时遵守规则,为您提供类似的行为.
However, you can use the .rules()
method to dynamically add, remove, or over-ride your rules at any time, giving you a similar behavior.
然后,您可以使用 .valid()
方法来测试表单.
Then you can use the .valid()
method to test the form.
将它们分别放入专用的click
事件处理程序中.
Put them each inside dedicated click
event handlers.
$(document).ready(function() {
// initialize the plugin
$("#form1").validate({
ignore : '*:not([name]),:hidden'
// no rules; rules are set dynamically below
});
// Save Button
$('#save_button').on('click', function() {
// dynamically set the rules
$('input[name="email"]').rules('add', {
required: true,
....
});
// remove all rules from the other fields
$('input[name="city"]').rules('remove');
// force a test of the form
$("#form1").valid();
});
// Submit Button
$('#submit_button').on('click', function() {
// dynamically set the rules
$('input[name="city"]').rules('add', {
required: true,
....
});
// remove all rules from the other fields
$('input[name="email"]').rules('remove');
// force a test of the form
$("#form1").valid();
});
});
概念验证演示: http://jsfiddle.net/x6YWM/
Proof-of-concept DEMO: http://jsfiddle.net/x6YWM/
如果您有许多字段,可以通过在它们上设置适当的类(例如.ruleset1
和.ruleset2
)来简化此过程.然后,您可以使用.rules()
方法将它们定位为一个组.只需记住,如果选择器针对多个元素,则需要将它们包含在jQuery .each()
中.
If you have many fields, you can make this easier by setting appropriate classes on them like .ruleset1
and .ruleset2
. Then you can target them as a group with the .rules()
method. Just remember that you'll need to enclose them inside a jQuery .each()
if the selector targets more than one element...
$('.ruleset1').each(function() { // target multiple elements
$(this).rules('add', { // apply the rules to each
required: true,
....
});
});
这篇关于有条件的jQuery验证插件规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!