Each time I start working on a new ASP.NET MVC web application, I'm not sure whether or not to use DataAnnotations
validation. Something about it feels wrong.
For example, let's say I have a UserService
which is passed a CreateUserModel
from the Create
action of the AccountController
. To ensure the user always supplies a name, I set the model's Name
property to have the [Required]
attribute. I'm now safe in the knowledge that the model binder won't ever give me a CreateUserModel
unless it has a name.
My problem is that for my UserService
to be a reusable component of my system, it can't rely on the fact the layer above is supplying valid data, and surely must also validate this data. The need for this is highlighted further when you consider that you may want to write a web service that fully reuses the UserService
(and wouldn't have the model binder to do all the data annotation validation for it).
So my question is: What is the best practice for this situation? Validate with data annotations and repeat that validation in the services? Validate only in the services and throw exceptions? A mix of both?
I hope my question isn't too subjective, I'm mainly trying to establish a consensus on whether moving the validation to data annotations is going to end up biting me in the end.