Removing Data Validation from MVC Controllers
Published on May 6, 2015 by Jamie Munro
Problem
You require custom data validation that cannot be accomplished via the built-in data annotation validation attributes - or - your data validation requires access to multiple properties in your model.
Solution
Many times the easy answer is to place the validation inside of your controller. However, I'm a strong believer of placing data validation outside of your controllers and within your data model. This is commonly accomplished by adding data annotation above the properties, such as the [Required] attribute. Another common way is to create your own validation attributes.
This example will use a third way and that is to implement the IValidatableObject interface. This interface defines a Validate function that must be implemented and because it is inside of your data model it has access to all properties within your model.
Tags: validation | ASP.NET | mvc5 | ivalidatableobject | validationcontext