Reputation: 2961
I'm looking at adding validation into my web app. Some models' validity depends on the state of other models in the app.
What are the benefits of using the data annotation framework over a service layer? It seems to me that the service implementation would be easier, however I understand the benefits of having validation close to the data.
Thanks!
Upvotes: 0
Views: 930
Reputation: 36297
MVC 3 / MVC 2 with .NET 4.0
Sounds like you want to use IValidatableObject, Scott Gu wrote a blog post about this.
What I normaly do if I have an Entity Framework model and I want to add custom validation to my object I do a partial class like this:
public partial class MyObjectModel : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (someNumberProperty > anotherNumberProperty)
yield return new ValidationResult(
"someNumber property is larger than anotherNumberProperty",
new[] { "someNumberProperty" });
if (someNumberProperty == 0)
yield return new ValidationResult("someNumber property cannot be 0",
new[] { "someNumberProperty" });
}
}
MVC 2
Here is a another post by Scott Gu on how to acheive model validation but you might want to look in to Custom Validation
.
Upvotes: 2