ASP.NET MVC 3 System.ComponentModel.DataAnnotations package provides a vast range of Data Annotations attribute, but there are certain scenarios where we need something which is very specific to our business requirements and we need to implement our own Validation Attributes. ASP.NET being an extensible framework which makes it possible for the developer to add user defined custom business validations using custom data annotations.
In this article I am going to demonstrate Custom Validation using ASP.NET Data Annotations.
First let us take a scenario where I need to create a form where I have to Draw a graph based on Date Range. In this form I have a graph control and From and To Date. Using the ‘Required’ DataAnnotation I can check if the Date is entered or not, Date Format can be validated using the RegularExpression Validator, but to validate some of the specific case like Comparing the From Date and To Date, Minimum date should not less than 2005, etc we need to create our Custom Validation Classes.
To start with this example lets first…
- Create a Telerik MVC 3 Web Application(Razor) from New Project. This is optional you can also use normal ASP.NET MVC 3 Web Project too.
- In the model folder create a Class ‘DateValidationAttribute.cs’ here we have to suffix the class with Attribute as this is a standard which is recognized by our ASP.NET MVC Application for any class to be used for DataAnnotation. Here the ‘Attribute’ suffix is suppressed and only the first part ‘DateValidation’ is used in the View Model Class as Data Annotation.
- Add a reference to System.ComponentModel.DataAnnotations.dll to our Project.
- Add a namespace reference of System.ComponentModel.DataAnnotation class in our DateValidationAttribute.cs class.
- In our DateValidationAttribute class implement ValidationAttribute base class, ValidationAttribute Class is the base class for all the System defined and user defined Custom Validation attribute classes.
With the steps given above our initial class will look something similar to the one below.
In this example I am creating a class named DateValidationAttribute.cs which extends base class ‘ValidationAttribute’ of System.ComponentModel.DataAnnotation package.
Now to provide the custom Validation Logic in this class we have to override the IsValid method of ValidationAttribute class and to make this class more generic, I have created a enum, which tells us what is the type of the validation I am going to use my DateValidation class.
And before we override the IsValid method we have to pass the initialization parameters to our DateValidationAttribute class constructor with the fromDate, toDate ValidationType, defaultErrorMessage and basePropertyName, here propertyNameToCompare is the property name of the ‘FromDate’. We are going to need ‘FromDate’ to compare with ToDate and Validate the Dates.
Now we are ready to override the IsValid method where we are going to implement the actual business rule validation. I have used Switch statement here to check which Validation Type the user is requested for.
IsValid method above returns the ValidationResult which is a member of System.ComponentModel.DataAnnotation. Here ValidationResult represents a container for the results of a validation request. Now with these pieces of code our DateValidationAttribute class is ready to consume. I understand that there are lots of tight coupling with the implementation class with this Validation component, this code is just for indicative usage of the Custom Data Annotation an extensibility feature provided by ASP.NET. In actual this class may require few changes.
Now lets come to my model class where I am going to use this as Data Annotation Attribute. In this example I have created a AccountModel.cs class and declared just two properties one is ToDate and another is FromDate for this example.
In this example I have used Telerik controls for DatePicker control. Telerik controls for MVC can be installed from Tools—>Extension Manager—> Online Templates. This Date controls I have created as a partial view in Views—>Shared folder, so that this can be used across my applications.
In the code above I am keeping the form method as post and Action to my DateValidation Action of HomeController. When the user clicks the Submit button the form Post the result to Controller and triggers the Validation logic defined in our Custom Validation Logic.
Now to embed this partial view into my Index page I have to write just one line as below in ‘Index.cshtml’ page.And that’s it in the View Side, if you are already familiar with MVC and Razor this code will be very simple for you to understand.
Now coming to my Home Controller, where I have created an Action method which Provides custom action on Validation failure and Success.
Just to keep this simple I am redirecting the user to About Page of my ASP.NET MVC Application, which is already provided. And for Validation failure I am keeping the user in the same page with the validation message displayed. Now lets assemble all the pieces of codes and test it. I am entering the invalid data where I am keeping the From Date more than To Date, with this I am getting the result as given in the screen below.
And for the built in Required Field Validation
If you can look into the code above for DateValidationAttribute class I have also provided an additional Validation for Date Range Validation, this can be used to restrict the user to enter dates in some Range based on the Business requirements. I am leaving it for you to implement. In order to Implement the same attribute multiple times we have to just fine tune some lines of my code as below.
But you can see above by default you cannot use the same Data Annotation Attribute multiple times in the same Property. To Get this working you have to provide additional Attribute to our DateValidationAttribute Class as below.
With AllowMultiple=true we can use the same DataAnnotation attribute multiple times in the same Property.
This code is just an extract of the actual implementation which is more structured and bigger. But I hope this example will give you a quick start on how to use the Custom Validation Data Annotation attributes. For further reading you can follow the links below from MSDN.
- Validation with the Data Annotation Validators (C#)
- Using Data Annotations for Model Validation
- Introducing Data Annotations Extensions
You can also download the sample code from here.
I am glad to announce that once again second time in a year I received MphasiS – Spirit of Winning award for the month of Dec 2011. This award is presented to the individual for living by the MphasiS Values and demonstrating the Winning Spirit.