Pages

Search This Blog

Tuesday, August 16, 2016

MVC Hidden controls are not validated

If you have used default MVC validation framework (using Annotations and jquery.validate.js) you might have faced issues with validating the controls which are hidden. As an example, in one of the scenario, I had a MVC view with too many controls, so to reduce its screen layout, I wrapped the MVC view in small expand-collapse divs, but this caused the validation to be disabled for the hidden fields.

After bit of investigation I found that it is due to the default settings of jquery.validate.js framework which explicitly excludes validation of all the hidden controls by setting the below option:
















To change the settings, I have injected custom code on window.load(). Example shown below:

$(window).load(function (e) {
    if ($('#<your formID>')[0] != undefined) {
        var validatorInitialised = $.data($('#<your formID>')[0], 'validator');
        if (validatorInitialised) {
            var settings = validatorInitialised.settings;
            //settings.ignore = ":hidden";
            settings.ignore = "";
        }
    }
});

This code first checks if the MVC page as a valid form to POST and that if there are validations applied on the page, changes the settings by removing the 'hidden' tag from the ignore list.



No comments:

Post a Comment