Disable required validation by JavaScript

前端 未结 7 885
半阙折子戏
半阙折子戏 2020-12-19 02:11

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 (

7条回答
  •  情书的邮戳
    2020-12-19 03:08

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

提交回复
热议问题