Disable required validation by JavaScript

前端 未结 7 863
半阙折子戏
半阙折子戏 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:03

    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
    
    //or this
    
    //or this
    
    
    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...

提交回复
热议问题