asp.net-mvcasp.net-mvc-2asp.net-mvc-2-validation

How to dynamically add/remove validators in ASP.NET MVC at runtime?


We are relying heavily on client-side validation using MicrosoftMvcValidation.debug.js in the our current application implementation.

We have form elements and form validators being defined in the database and loaded from the database at runtime. We have viewmodel properties Answer1, Answer2, Answer3, etc., and up until now all fields were required, so we had the [Required] attribute on each of them, but now we need to apply this required annotation at runtime based on database settings since some of the questions are optional.

I don't want to do any reimplementation of validators themselves, I just want to either dynamically remove the [Required] attributes and/or their effects at runtime, or else dynamically add them at runtime.

Using ASP.NET MVC 2.


Solution

  • Add the [Required] attribute to any fields that could be required. As long as you don't bind a control client-side, you will bypass client validation without problems. On the server side post-back action, loop through the ModelState (which implements IDictionary) and clear the errors on the ModelState for the validators that you want to bypass.

    foreach( var validator in ModelState){
       if( validator.Key == "Validator_To_Bypass")
           validator.Value.Errors.Clear();
    }