Please see my other MVC articles.
Enforcing Model-level validation.
MVC enables validation to be performed at the model-level by implementing the IValidatableObject interface.
Once you’ve defined Validate(), your routines then may perform custom validation using the Model’s properties.
To illustrate this feature, I’ll implement a routine to ensure the territory entered is one of the acceptable values – “OR.”
First, I’ll update my Model to implement the IValidatableObject interface.
Next, I’ll implement the validation method with a signature that returns the interface type and a ValidationContext variable.
They important part is the return statement – notice I’m using the yield keyword to return all error messages to the IEnumerable collection.
Now when I enter a value that isn’t one of the accepted territories, I get an error message.