- MVC Validation – Part 1 – Model Data Annotations
- MVC Validation – Part 3 – Client-Side Validation
- MVC Validation – Part 4 – Styling the Validation Controls
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!!)
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:
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:
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