How do I remove the 'required' rules from all form inputs in jQuery Validate?
As above, how can I remove all of the required rules from a form using jQuery Validate?
This is what I have at present:
var settings = $('form').validate().settings;
//alert(settings.rules.toSource());
for (var i in settings.rules){
开发者_Python百科 alert(i);
delete settings.rules.i;
// ^ not sure about how to do this properly,
// and how to just delete the 'required' rule and keep the rest intact
}
The function native to jQuery Validate returns an undefined error:
$("input, select, textarea").rules('remove','required');
And if you don't want to mess with validate's internal settings, you can use the public function in this way:
$('input, select, textarea').each(function() {
$(this).rules('remove', 'required');
});
Note that leaving out the second parameter (required) would remove all the rules, not just the "required".
As can sometimes be the case, I appear to have stumbled on the answer just after resorting to posting on here.
for (var i in settings.rules){
delete settings.rules[i].required;
}
Works.
When you need to remove a required input, you need also delete the attr of your input, test this.
$('element').rules('remove', 'required');
$('element').removeAttr('required');
You can disable jquery validate rules globally for client side validation using the ignore property (see validator options https://jqueryvalidation.org/validate/). This is useful for testing server side validation.
You can disable all rules
$.validator.setDefaults({
ignore: ":hidden, input, select, textarea"
})
This is a jquery selector so you also do,
$.validator.setDefaults({
ignore: ":hidden, input[required], select[required], textarea[required]"
})
For additional inputs just add as needed.
You can also remove html validation with something like this for dev environment (since its a slow selector):
$("*[required]").removeAttr("required");
$("*[maxlength]").removeAttr("maxlength");
$("*[minlength]").removeAttr("minlength");
$("*[pattern]").removeAttr("pattern");
This is to remove / reset the red validation text too.
function RemoveJQVRule(rulename, inputname) {
$(`[name="${inputname}"]`).rules('remove', rulename);
$(`#${inputname.replace('.', '_')}-error`).html("");
}
Usage:
RemoveJQVRule('required', 'AddressVM.CityId')
The dot is when dealing with objects, it can work for simple names normally like 'Address'.
精彩评论