RSS

MVC Validation – Part 2 – Custom Validation

20 Jun

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

Advertisements
 

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

 
%d bloggers like this: