0

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.

Jon Davis
  • 6,562
  • 5
  • 43
  • 60

2 Answers2

3

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();
}
CJensen
  • 86
  • 3
0

Seems one can create a custom class that inherits ValidationAttribute that can determine at runtime how or whether validation is done. This is one way of accomplishing this requirement.

Jon Davis
  • 6,562
  • 5
  • 43
  • 60
  • There is a better way for what you are doing. Can't answer now as its rather lengthy. Will post code tonight. – John Farrell Jul 20 '11 at 19:21
  • @jfar 2 years later and I'm curious what you had planned on posting. Running up against the same problem with MVC4: http://stackoverflow.com/questions/18919758/dynamically-apply-validation-rules-at-runtime-with-asp-net-mvc-4 – joelmdev Sep 20 '13 at 16:40
  • @jm2 I emailed you via your contact page on your website. – John Farrell Sep 22 '13 at 22:35
  • I received the email instead of jm2. jfar, it was @jm2 who followed up asking for an update. jm2 please contact jfar with your contact info, or send me an e-mail and I'll forward what jfar sent me. Thanks guys. – Jon Davis Sep 22 '13 at 22:43