Disable required validation by JavaScript

Tobias picture Tobias · Sep 12, 2011 · Viewed 41.6k times · Source

I have a create form to create an object. The create model has some properties that are only visible (.hide, .show()) if a checkbox is checked and that are marked required (by Attribute in Model).

Unfortunatly when the checkbox is not checked, the required validation is performed on the properties hidden.

How can I disable the required validation for this properties?

I tried setting the data-val property of the input element to false but this does not work.

Some an idea?

Thanks in advance Tobias

UPDATE:

Here is the java script code. The data-val property is set correctly to false. it seems that validation does not care of this property. there is also the data-val-required attribute but there is a text i could not backup.

$(function () {
                $("#MyCheckbox")
                    .change(function () {
                        if (this.checked) {
                            $("#divWithChildProperties [data-val]").attr("data-val", true);
                            $("#divWithChildProperties ").show();
                        }
                        else {
                            $("#divWithChildProperties [data-val]").attr("data-val", false);
                            $("#divWithChildProperties ").hide();
                        }
                    })
            });

Answer

bbak picture bbak · Sep 12, 2011

I've handled cases like this with a custom Validation Attribute. Instead of using the Required attribute for properties you could make a RequiredIf attribute and make some of your properties required only if another property is a certain value.

Here is a post about creating an attribute like this (the example in the middle of the page under the 'A more complex custom validator' section): http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

If your checkbox represents a property in your model this should work fine.

If you don't want to handle this with a new validation attribute you will have to do a few more things than just change the data-val attribute to false. When jQuery validate first parses your form it stores values in the form's data. So simply changing data-val isn't enough. You will additionally have to remove the stored validation data and reparse the form. Here's an example:

// Do this after you've removed/modified the data-val attribute
$('selector for your form').removeData('unobtrusiveValidation');
$('selector for your form').removeData('validator');
$.validator.unobtrusive.parse('selector for your form');