MVC: Custom Validation

Using Custom Validation within a View

While MVC provides many robust attributes within a Model to satisfy many validation scenarios, some situations exist which require custom logic to validate a user’s input.

This article will illustrate how to implement your own routines to validate user input.

First, create a new class which contains a “using System.ComponentModel.DataAnnotations,”inherits “ValidationAttribute,” and has a similar signature.

1-mvc-4-custom-validation

Now, to tie the custom validation class to the Model, you must add the following attribute.

2-mvc-4-custom-validation

When the user attempts to submit the form, your custom validation routine will warn the user should their input violate your business rules.

3-mvc-4-custom-validation

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