Monthly Archives: June 2011

MVC Validation – Part 2 – Custom Validation

In Part 1 we saw how easy it was to add Data Annotations to our model classes in order to persist validation to the presentation layer.  However what if I wanted to perform my own custom validation on attributes of my model.

Using the example from Part 1 heres how:

Step 1 – Create a new validator class

In Part 1 we created a Customer Object and applied some validation.  You may remember that the Customer object contained a property called ‘Balance’ which as yet enforces no validation.  Therefore we are going to apply out own custom validation to this property which enforces the following rule:

If the Balance Value is less than or equal to 10.00 then display the message ‘The Account is low!!’

Right, first we need to create a new class which will contain out validation logic, so create a new class called ‘BalanceValidator’ within a folder called ‘Validation’ (Just to keep things neat and tidy!!)

Create Validation Class

Step 2 – Write Validation Logic

Again, ensure you have added the ‘System.ComponentModel.DataAnnotations’ namespace to your class.

Next inherit the ‘ValidationAttribute’ class and override the IsValid method

Finally add the validation logic to the IsValid method.

Your BalanceValidator class should now look something like:

BalanceValidator Class

Step 3 – Apply Validation

We now have out custom validation logic so all that is left to do now is apply it to out Balance Property of the Customer Class.

Add the new BalanceValidator attribute to the Balance Property as shown below:

BalanceValidator Attribute

Step 4 – Run the Application

Now as long as you are performing server-side validation (Part 3 will go in Client Side and Server Side Validation) you should be able to enter a value less than 10.00 into the Balance text box and see our Message ‘The Account is low!!’ appear

Running the application


MVC Validation – Part 1 – Model Data Annotations

Most Web Applications will require some form of user input and it is often a requirement to validate this input.  With ASP.NET web forms validation could be performed using the validator controls and were often implemented as an afterthought e.g. RequiredFieldValidator, RegularExpressionValidator etc.

Within the world of MVC validation takes another approach.  Using Data Annotations we can apply validation directly to the model objects easily, allowing the validation rules to filter through to the objects that consumes these model objects.

In Part 1 of my posts on MVC Validation I will provide a step by step guide to applying validation to a model object within my solution.

Step 1 – Create an MVC Project

Before we can apply the validation lets create a simple MVC project and when prompted set the view engine to Razor.

The project template will look similar to this:

MVC Solution Template

In order to ensure we can use Data Annotations for enforce our validation make sure there is a reference to System.ComponentModel.DataAnnotations
Step 2 – Create our model class and apply the validation

Within the Models Folder add a new class named Customer and create a few properties e.g.

Customer Class

Also add the using statement for the DataAnnotations reference added earlier

So now we have our model object we can use data annotations to apply validation to properties of the object.

For example, assume that the Forename and Surname and required fields and that the length cannot exceed 50 characters.  Also assume that the email address is also required and that the users input for the email address must be validated using regular expressions.  To enforce these rules we could modify the class using the following annotations:

Validation Decorators

Note: Other annotations available are:

Range: Validates whether a value falls between a minimum and maximum value

DataType: Validates whether the value matches a certain type e.g. could be used to ensure the user supplies a valid date time value

Step 3 – Create a controller and view then run the application

The final stage is just to create a controller class to test the validation.

Right-click on the Controllers folder then click Add à Controller…

Add the following two Create methods

Controller Class

Notice the Create() with the [HttpPost] annotation.  This is the method that is called when the user posts data from the Customer View back to the Server and so this is the method which will invoke the validation check.

Simply call ModelState.IsValid to determine whether or not the user’s input conforms to the validation rules
imposed on the model.

To create the View (our user interface), right-click the Create() Method in the controller and click Add View…

Add View Screen

Click ‘Create a strongly-typed view’ and select our Customer model object.  Also ensure that the Scaffold template is set to ‘Create’.

All that is left now is to run the application.  You may need to modify the invoked URL to be
something like http://localhost:50712/Customer/Create  so that our Create new Customer View isinvoked

Try leaving the Forename and Surname fields blank and putting rubbish into the email field then hitting the Create button, Voila!! Validation without any Validator Controls in sight