MVC: Validation – Model

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.

1-mvc-validation-model

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.

2-mvc-validation-model

Now when I enter a value that isn’t one of the accepted territories, I get an error message.

3-mvc-validation-model

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s