ASP.NET MVC 3: programmatically add DataAnnotation (RequiredAttribute) to view model

asp.net, asp.net-mvc, asp.net-mvc-3, validation

Solution

Cannot be done using DataAnnotations as these are implemented at compile time and cannot be added dynamically. You can either

Create different View Models that have the proper annotations

or

Have a service that you send the view model to that checks the model based on the action that it is coming from and return a list of validation errors that you can append to your model state

or

Put a property on the ViewModel such as `string IsBeingUsedFor` and use that in combination with a RequiredIf DataAnnotation. Here is an example of a library already build that uses conditional DataAnnotations. Then you can say, [RequireIf("IsBeingUsedFor", "Action_A")]

These aren't necessarily all of the options, but the some of the cleaner ones. You could do this all in JavaScript, but you will lose server side validation and could open up some holes in your application if a 'bad person' submits the form and bypasses client side validation.

Problem

I am using javascript unobtrusive validation. I have a view model that I am re-using for several forms, and in some of the forms, some properties on the view model are required. On other forms they shouldn't be. Is there a way to programmatically set [Required] on properties, so that I can accomplish this? Thanks!

Original source