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.
ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values. RegularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
Alternatives to built-in attributes If you need validation not provided by built-in attributes, you can: Create custom attributes. Implement IValidatableObject.
Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.
There are two types of validations: Server side Validations. Client Side Validations.
I perform all my validation in the service layer, using a combination of manual validations (if x == y) and using Data Annotations.
To use Data Annotations in your service layer, you have to manually use the Validator class using the TryValidateObject()
method. A good example of this can be seen here.
You then have to pass your validation errors down from your service layer to your controller, and have your controller add each error to the Model state error list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With