Multiple MetadataType validation rule sets using DataAnnotations with ASP.Net MVC

2.2k Views Asked by At

I am using DataAnnotations and MetadataType in ASP.Net MVC to validate the creation of one of my custom objects through a form on our www site. It's working really well.

But now we also need to be able to create the same object through a form in our internal admin site.

However, the validation rules are slightly different in that some fields are mandatory on the www site that are not mandatory when we complete the form ourselves through our internal admin system..

Further, I'd like to be able to give the same field different DisplayNames and different validation messages depending on which site/form the data is being collected from etc.

How can I essentially have two different MetadataType's and specify which one I wish to use when validating within the admin site, versus the www site.. I.e. two different sets of validation rules and the ability to specify which one I am validating against..

I have employed my MetadataType's using Buddy (partial) classes, as my objects are auto-generated by LINQ to SQL.

2

There are 2 best solutions below

1
On
6
On

I have been in the same situation before. I searched around at the time but found that there was no solution that would give you two sets of validation rules on the same class.

The way I tackled it was to use the view models. You have your "core" model classes and you want different UI's (in this case web and admin UI's) to have different validation rules. You wouldn't need buddy classes for your model classes in this case as you don't want to apply validation rules on the model class itself, instead you will need to inherit from your model class to create two view model classes, one for web and the other for admin interface, and apply the validation rules using DataAnnotations differently on those classes as per your needs. You can also "enhance" your view model classes with any extra, UI specific, attributes.

I know this solution is not perfect as you will have your validation rules on two different places and it's usually not advisable but it works and it's not that bad practically especially if the application isn't very large. The only other solution is to check manually the place user is using is coming from (web or admin) and then adding model state errors according to that. But I wouldn't recommend doing it that way.

I would love to hear if somebody has a better solution for this.