jQuery 仅在提交时验证规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5252373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:49:29  来源:igfitidea点击:

jQuery validate rule ONLY AT SUBMIT

jqueryjquery-validate

提问by Michael

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.

假设我有一个查找城市、州位置的表格。如果用户输入不正确的城市、州,我希望表单能够根据用户输入检查数据库,并查看输入是否有效。如果不是,我希望用户得到提示。

So form Validate is the plugin for me.

所以表单验证是我的插件。

$("#form").validate({
    rules: {
       citystate: {
           required: true,
           myCustomAjaxSyncronousCheckAgainstDBRule: true
       }

    submitHandler: function(form) {
        if ($("#form").valid()) {
            form.submit();
        }
    }
});

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.

现在说这个表单必须在我网站的 4 个不同的地方使用,所以重构 myCustomAjaxSyncronousCheckAgainsDBRule(顺便说一句假名)并在我的网站上使用相同的代码 4 次会很糟糕。所以这就是我在 JS 文件中创建自定义规则的原因。但是有没有办法只能在提交时检查规则。因为如果存在无效的用户输入,它会在每次击键时检查它,这可能非常麻烦。特别是因为我有 jQuery.ui.autocomplete 运行不连贯。

采纳答案by sabotero

As an alternative an a more straightforward way you can pass a function to the onfocusoutand onkeyupsettings of the jquery.validator to decide if an element has to be validated in those events or not, as this :

作为替代,一种更直接的方法是您可以将函数传递给jquery.validator的onfocusoutonkeyup设置,以决定是否必须在这些事件中验证元素,如下所示:

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);
    }
}

回答by iivel

All of the validations can be set independently (onclick, onkeypress,onsubmit,etc.)

所有验证都可以独立设置(onclick、onkeypress、onsubmit 等)

Demos and details are available on the docs site http://docs.jquery.com/Plugins/Validation/validate

演示和详细信息可在文档站点 http://docs.jquery.com/Plugins/Validation/validate 上获得


$("#form").validate({
   onkeyup: false,
   onclick: false
})

回答by Rodrigo Manguinho

$.extend($("#form-id").validate().settings, { 
    onkeyup: false, 
    onfocusout: false 
});

回答by Ryley

Here's an idea that might work: separately bind the keyup function for your field that you don't want the keyup event to be validated on, and have it not bubble:

这是一个可能可行的想法:为您不希望验证 keyup 事件的字段单独绑定 keyup 函数,并使其不冒泡:

$('#citystateID').bind('keyup',function(){
   return false; 
});

I couldn't figure out how to bind the validator specific events (focusin and focusout), so it would still run validations whenever focus left your "citystate" input, but it's closer to what you wanted?

我不知道如何绑定验证器特定事件(focusin 和 focusout),所以只要焦点离开你的“citystate”输入,它仍然会运行验证,但它更接近你想要的?

I briefly tested this here: http://jsfiddle.net/svUdp/seemed to work alright (watch your console to see what happens - lots of events being triggered, but not so many validates).

我在这里简要测试了这个:http: //jsfiddle.net/svUdp/似乎工作正常(观察你的控制台看看会发生什么 - 触发了很多事件,但没有那么多验证)。

回答by Mike Munhall

If you're trying to get a particular validation method to fire ONLY on the submit event while allowing other validation methods to fire normally (e.g., on the onkeyup event), then you can dynamically add the rule when the submit event fires, then remove it after the validation is performed. The ordering of the bindings is important; keep them in order.

如果您试图让特定的验证方法仅在提交事件上触发,同时允许其他验证方法正常触发(例如,在 onkeyup 事件上),那么您可以在提交事件触发时动态添加规则,然后删除它在执行验证后。绑定的顺序很重要;让他们井井有条。

$('#form').bind('submit', function(event) {
    $('#citystate').rules('add', {myCustomAjaxSyncronousCheckAgainstDBRule: true});
    event.preventDefault();
});

$('#form').validate({
    rules: {
        citystate: { required: true }
    }
});

$('#form').bind('submit', function(event) {
    $('#citystate').rules('remove', 'myCustomAjaxSyncronousCheckAgainstDBRule');
    event.preventDefault();
});

回答by adgiovanni

$("#form").validate({ onfocusout: false, onkeyup: false, onclick: false });

$("#form").validate({ onfocusout: false, onkeyup: false, onclick: false });