我无法弄清楚为什么form2验证失败但是form1通过验证(使用jQuery验证插件)。如何使用下面的代码使form1失败验证?
HTML
<form id="form1" method="get" action="">
<input type="text" id="viewName1">
<h3></h3>
</form>
<form id="form2" method="get" action="">
<input type="text" id="viewName2" required>
<h3></h3>
</form>
JAVASCRIPT
$('#form1').validate({
rules: {
viewName: 'required'
},
messages: {
viewName: '* view name is required'
},
submitHandler: function () {
$('#form1 h3').text('Form1 valid');
},
invalidHandler: function (event, validator) {
$('#form1 h3').text('Form1 invalid');
}
});
$('#form1').submit();
$('#form2').validate({
submitHandler: function () {
$('#form1 h3').text('Form1 valid');
},
invalidHandler: function (event, validator) {
$('#form1 h3').text('Form1 invalid');
}
});
$('#form2').submit();
答案 0 :(得分:1)
它不起作用,因为您的输入元素没有name
属性。这是插件的要求。
See the "markup recommendations" section of the docs:
“输入元素的
name
属性是'必需的', 如果没有它,验证插件就无法运行。“
$('#form1').validate({
rules: {
viewName: 'required' // <-- "viewName" is the 'name' attribute, not id
},
messages: {
viewName: '* view name is required' // <-- "viewName" is the 'name' attribute, not id
},
submitHandler: function () {
$('#form1 h3').text('Form1 valid');
},
invalidHandler: function (event, validator) {
$('#form1 h3').text('Form1 invalid');
}
});