我有一个使用 jQuery 验证的项目。 这是我的代码:
<script type="text/javascript" src="Scripts/jquery-1.5.1.js"></script>
<script type="text/javascript" src="Scripts/jquery.validate.js"></script>
<form action="/" id="MyForm" onsubmit="greeting()">
<input type="checkbox" value="val1" name="dner" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function greeting() {
return $("#MyForm").valid();
}
$(document).ready(function () {
$("#MyForm").validate({ onsubmit: true }); //If comment this code line, it work!!!
$.validator.addMethod("MyFunction", function (value, element) {
if ($("input:checked").length > 0) { return true } else { alert("Пустое поле"); return false; }
},
"");
$("#MyForm").rules("add", { dner:{ MyFunction :true}});
});
</script>
当我注释一行代码时,它起作用了。这非常重要,因为在我的项目中我有一套新的验证规则,并且我无法重新制定它。如何向现有规则添加新规则?
最佳答案
您的代码:
//If comment this code line, it work!!!
$("#MyForm").validate({ onsubmit: true });
如果您注释掉整行,您将删除插件的初始化方法!
这是一个有争议的问题,因为您的代码在这两种情况下都不起作用。请参阅here或here .
您必须纠正以下问题:
<小时/>1) onsubmit: true
已经是默认 行为,因此将其设置为 true
,你破坏了插件。如果您希望在单击提交
按钮时进行验证,请忽略此选项。
See documentation for onsubmit
:
<小时/>onsubmit (default: true):
Validate the form on submit. Set tofalse
to use only other events for validation. Set to a Function to decide for yourself when to run validation. A booleantrue
is not a valid value.
2) 您的代码:$("#MyForm").rules("add"...
.
您不应该将 .rules()
方法附加到 form
。您仅将其附加到 field
元素...
$('input[name="dner"]').rules("add", {
MyFunction: true
});
参见documentation .
要同时将此方法应用于多个字段,请使用 jQuery .each()
...
$('input[type="checkbox"]').each(function() {
$(this).rules("add", {
MyFunction: true
});
});
<小时/>
3) 您不需要内联 submit
处理程序:onsubmit="greeting()"
。使用 jQuery 时完全不需要内联 JavaScript。此外,submit
处理程序会干扰插件的内置 submit
处理程序。如果您在使用此插件时需要在 submit
事件上执行某些操作,请使用 submitHandler
回调函数...
submitHandler: function(form) {
// fire this code when a valid form is submitted
return false; // prevent default form action, e.g. when using ajax()
}
如果您需要在表单无效时触发代码,请使用 invalidHandler
回调...
invalidHandler: function(event, validator) {
// fire this code when an invalid form is submitted
}
参见documentation例如。
<小时/>4)您的自定义方法可以压缩...
$.validator.addMethod("MyFunction", function (value, element) {
return ($("input:checked").length > 0)
}, "Пустое поле");
如果您更愿意使用 alert()
而不是 label
消息,您可以将其放回去。尽管我不建议在任何现代设计中使用 alert()
。
应用了所有更改的演示:http://jsfiddle.net/sqKta/
关于jQuery 验证插件。向现有规则添加新规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19005548/