jQuery仅在提交时验证规则 [英] jQuery validate rule ONLY AT SUBMIT
问题描述
说我有一个查找城市,州位置的表格.如果用户输入了不正确的城市,州,我希望表格能够对照用户输入检查数据库,并查看输入是否有效.如果不是,我希望用户得到提示.
Say i have a form that looks up city, state locations. if the user enters an incorrect city, state, i want the form to be able to check the database against the users input, and see if the input is valid or not. If it is not, i want the user to be prompt.
因此Form Validate是我的插件.
So form Validate is the plugin for me.
$("#form").validate({
rules: {
citystate: {
required: true,
myCustomAjaxSyncronousCheckAgainstDBRule: true
}
submitHandler: function(form) {
if ($("#form").valid()) {
form.submit();
}
}
});
现在说此表格必须在我的网站的4个不同位置使用,因此重构myCustomAjaxSyncronousCheckAgainsDBRule(假名btw)会很麻烦,并且在我的网站上有4次相同的代码.因此,这就是为什么我在JS文件中创建了自定义规则的原因.但是有一种方法只能在提交"时检查规则.由于如果有无效的用户输入,它将在每次击键时对其进行检查,这可能非常麻烦.尤其是因为我有jQuery.ui.autocomplete运行不同步.
Now say this form has to be used in 4 different places in my website, so it would suck to refactor out the myCustomAjaxSyncronousCheckAgainsDBRule (Fake name btw) and have the same code 4 times throughout my website. So that is why i created a custom rule in the JS file. But is there a way that the rule CAN ONLY be checked at Submit time. Since if there is an invalid user input, it will check it at EVERY key stroke, which can be quite cumbersome. Especially since i have jQuery.ui.autocomplete running inconjuction.
推荐答案
作为一种更直接的方法,您可以将函数传递给jquery.validator的onfocusout
和onkeyup
设置,以确定是否一个元素必须在这些事件中进行验证,因为:
As an alternative an a more straightforward way you can pass a function to the onfocusout
and onkeyup
settings of the jquery.validator to decide if an element has to be validated in those events or not, as this :
jQuery.validator.defaults.onfocusout = function (element, event) {
// detectect if is the element you dont want validate
// the element has to have the attribute 'data-control="mycitycontrol"'
// you can also identify your element as you please
if ($(element).data("control") === "mycitycontrol") return;
if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) {
this.element(element);
}
}
jQuery.validator.defaults.onkeyup = function (element, event) {
// detectect if is the element you dont want validate
// the element has to have the attribute 'data-control="mycitycontrol"'
// you can also identify your element as you please
if ($(element).data("control") === "mycitycontrol") return;
if (event.which === 9 && this.elementValue(element) === "") {
return;
}
else if (element.name in this.submitted || element === this.lastElement) {
this.element(element);
}
}
这篇关于jQuery仅在提交时验证规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!