How do I remove the 'required' rules from all form inputs in jQuery Validate?

Viewed 41576

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){
    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');
5 Answers

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'.

Related