问题描述
我想分两部分验证一种形式,当我单击btn
按钮时,验证已正确完成,但是当我单击btnn
时,它不起作用,并且始终验证field1
I want to validate one form in two part, when I click the btn
button then validation is done properly, but when I click btnn
it's not working and always validates field1
这是我的代码
jQuery:
$(document).ready(function() {
$("#form1").validate({
rules: {
field1: "required"
},
messages: {
field1: "Please specify your name"
}
})
$('#btn').click(function() {
$("#form1").valid();
});
$("#form1").validate({
rules: {
field2: "required"
},
messages: {
field2: "Please specify your name"
}
})
$('#btnn').click(function() {
$("#form1").valid();
});
});
HTML
<form id="form1" name="form1">
Field 1: <input name="field1" type="text" />
Field 2: <input name="field2" type="text" />
</form>
<div>
<input id="btn" type="button" value="Validate"/>
<input id="btnn" type="button" value="Validate"/>
</div>
有什么建议吗?
推荐答案
通过设计,您不能在同一窗体上两次调用.validate()
方法. .validate()
方法用于初始化,第二个实例将始终被忽略.
By design, you cannot call the .validate()
method twice on the same form. The .validate()
method is used for initialization and the second instance will always be ignored.
您在这里有两个选择:
- 将第2部分放入其自己的
<form>
容器中.
- Put part 2 into its own
<form>
container.
OR
- 其他一些技巧,例如显示/隐藏表单字段,或使用
.rules()
方法根据单击的按钮动态添加/删除规则.如果要显示/隐藏这些字段,则在.validate()
的同一实例中声明所有规则,并利用此插件的默认行为,即忽略所有隐藏的字段.
- Some other trick like showing/hiding the form fields, or using the
.rules()
method to add/remove rules dynamically depending on which button is clicked. If you're showing/hiding these fields, then declare all rules in the same instance of.validate()
and leverage the default behavior of this plugin, which is to ignore all hidden fields.
由于您尚未透露多部分表格的工作概念,也未希望分两部分进行验证,因此,我将向您展示最简单的解决方案,即建议#1.
Since you have not revealed the working concept of your multi-part form, or the purpose of wanting to validate in two parts, I will show you the simplest solution, which is suggestion #1.
jQuery :
$(document).ready(function() {
$("#form1").validate({ // initialize `form1`
rules: {
field1: "required"
},
messages: {
field1: "Please specify your name"
}
});
$('#btn').click(function() {
$("#form1").valid();
});
$("#form2").validate({ // initialize `form2`
rules: {
field2: "required"
},
messages: {
field2: "Please specify your name"
}
});
$('#btnn').click(function() {
$("#form2").valid();
});
});
HTML :
<form id="form1" name="form1">
Field 1: <input name="field1" type="text" />
</form>
<form id="form2" name="form2">
Field 2: <input name="field2" type="text" />
</form>
<div>
<input id="btn" type="button" value="Validate"/>
<input id="btnn" type="button" value="Validate"/>
</div>
这是另一个答案,显示了如何完成多步骤表单:
Here is another answer showing how multi-step forms can be done:
https://stackoverflow.com/a/20481497/594235
这篇关于jQuery验证:验证表单分为两部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!