Disable required validation by JavaScript

2019-01-26 08:40发布

问题:

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

回答1:

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


回答2:

You can use following JQuery to remove all validation rules of your element

$('#ElementId').rules('remove');

Same way you can use class name like,

$('.ElementClassName').rules('remove');

If you want to remove specific rule, do like this

$('#ElementId').rules('remove', 'required');


回答3:

The unobtrusive javascript plugin provided by MVC doesn't process the data properties on the fly. Instead, it parses the results on document ready and caches them.

Try calling $.validator.unobtrusive.parse(myForm) on your form after modifying the property in question to see if it gives you expected results.



回答4:

Unobstrusive validation looks for this attribute data-val="true"

I guess, that if you do a $('#mycheckbox').data('val','false'), the validation will skip a item with that id.

Probably there is a more appropriate way to do it, but if not, take this.

cheers.



回答5:

There are many ways to disable unobtrusive validation in Javascript but most of them seems a bit hackish...

  1. Recently found that you can do it with submit button. Check this link for info

http://www.nitrix-reloaded.com/2013/09/16/disable-client-side-validation-on-a-button-click-asp-net-mvc/

//this
<script type="text/javascript">
  document.getElementById("backButton").disableValidation = true;
</script>
//or this
<input type="submit" name="backButton" value="Back" 
 title="Go back to Prev Step" disableValidation="true" />
//or this
<input type="submit" name="backButton" value="Back"
 title="Go back to Prev Step" class="mybtn-style cancel" />
  1. Another way that is more flexible but more complicated : you can disable unobtrusive validation by setting the data-val attribute to false. But there is a trick...

Unobtrusive validation data is cached when the document is ready. This means that if you have data-val='true' at the beginning and that you change it later on, it will still be true.

So, if you want to change it after the document is ready, you also need to reset the validator which will erase the cached data. Here is how to do it :

disableValidation: function () {
    //Set the attribute to false
    $("[data-val='true']").attr('data-val', 'false');

    //Reset validation message
    $('.field-validation-error')
    .removeClass('field-validation-error')
    .addClass('field-validation-valid');

    //Reset input, select and textarea style
    $('.input-validation-error')
    .removeClass('input-validation-error')
    .addClass('valid');

    //Reset validation summary
    $(".validation-summary-errors")
    .removeClass("validation-summary-errors")
    .addClass("validation-summary-valid");

    //To reenable lazy validation (no validation until you submit the form)
    $('form').removeData('unobtrusiveValidation');
    $('form').removeData('validator');
    $.validator.unobtrusive.parse($('form'));
},

You don't need to reset all the messages, input styles and validation summary to be able to submit the form but it's useful if you want to change the validation after the page is loaded. Otherwise, even if you change the validation, the previous error messages will still be visible...



回答6:

The default DataAnnotationsModelValidatorProvider adds a Required attribute to all value types. You can change this behavior by adding the code in this answer.



回答7:

You could implement a custom validator like "RequiredIf".

That will keep your model design quite obvious (unlike client-side-only solutions proposed). This allows you to keep the validation logic separate from display logic (that's what MVC is all about).

See this answer : RequiredIf Conditional Validation Attribute

and ultimately that blog post : Conditional Validation in ASP.NET MVC 3

cheers!