Ignoring certain validation rules with jQuery validate

笑着哭i 提交于 2019-12-13 16:16:46

问题


I am using jQuery validate plugin to do custom validations on my forms. For one particular type of form, the user has the option to submit the form, or they can also save the form without submitting. I was able to use $('form.validate').validate().cancelSubmit = true; to suppress validation in the onClick handler for the save button, and life was good.

However, one of the custom validations that was written enforces that people must enter legit characters (i.e. it enforces that you use valid ascii characters). I want to continue to enforce the ascii validation, because if I don't, people are able to save bad data to the database (which subsequently messes up integrations we have running).

Basically I want to enforce all rules except required: true. I see that you can use the ignore option when setting up the validation on the form $('form.validate').validate({ignore : ".required"}); but this only seems to work when you are initially setting up the validation. When I try to do that when a user clicks the button, it doesn't seem to do anything.

I've seen some posts about similar things but usually related to ignoring hidden fields. Does anybody know the correct syntax / method I need to use to ignore the required rule upon button click? Any help would be appreciated.


回答1:


You could use the rules('remove') method to remove your rules dynamically. Something like this on your "save" button.

$('#save').click(function () {
    $('#myform').find('.myclass').each(function () {
        $(this).rules('remove', 'required');
    });
    // your code to save form
});

Demo: http://jsfiddle.net/NqT2V/

Important NOTE: As per rules('remove') documentation, "Manipulates only rules specified via rules-option or via rules('add')." In other words, this will not work if your rules are added inline via class="required".


And the rules('add') method to add the rules back just before submit...

$('#submit').click(function (e) {
    e.preventDefault();
    $('#myform').find('input').each(function () {
        $(this).rules('add', 'required');
    });
    $('#myform').submit();
});

Demo: http://jsfiddle.net/3G8cN/



来源:https://stackoverflow.com/questions/14566172/ignoring-certain-validation-rules-with-jquery-validate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!