Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Data Annotations really a good idea for validation?

As I'm learning more and more about ASP.NET MVC the more I am introduced to Data Annotations.
Specifically in MVC they are used for validation and this gives me some concerns.
The biggest is due to the fact that I like to keep my model as POCOs and as clean as possible.
Now what if I have those model classes shared across multiple projects in a solution (i.e. web front end, desktop app, web services)?
Basically I am concerned that annotations specific for my MVC front end app could influence some other projects like Dynamic Data, etc. I already have my Business Objects separated from my database model (in this case LINQ2SQL) so I don't worry about annotations having influence on my DAL, but I'm wondering if my fear about other projects is legitimate.

Also I think that tying a required error message to your model is a bit insane.

I suppose the problem would be solved if I created separate models for each project (web, desktop, web service, etc.) but this would be practically a direct copy of my currently shared model. Is it the right path?
It would have big impact on my solution (much mapping from one model to another happening).

What do you think?
I would like to hear what you consider good and bad use of Data Annotations.

like image 327
Piotr Owsiak Avatar asked Sep 27 '10 21:09

Piotr Owsiak


2 Answers

I find Data Annotations convenient for models where the rules never change depending on context such as an email address.

But for more complex validation (multiple fields, requires DB access, etc.) I use the visitor pattern described in Entity validation with visitors and extension methods.

like image 63
Todd Smith Avatar answered Oct 23 '22 06:10

Todd Smith


Really, really good question. Especially since all the shiny demo example apps are built around DataAnnotations handling all the validation because its such a nice, shiny selling point. And who likes doing validation anyhow?

I think the better way to look at this is that they should be part of a fuller validation solution, both for the structural reasons you mention as well as their limitations -- how do you validate stuff like "Is this user name unique?" or "Is this manager allowed to assign this task to this employee?" using data annotations?

like image 22
Wyatt Barnett Avatar answered Oct 23 '22 05:10

Wyatt Barnett