ARTICLE

Creating Custom Validation Attribute For Data Annotation

Posted by Jignesh Trivedi Articles | Learn .NET June 27, 2012
In .net 4.0, namespace System.ComponentModel.DataAnnotations allow you to create new attribute and with the help of this you can validate the data as per your requirement.
Reader Level:
Download Files:
 

Introduction

In .Net 4.0, namespace System.ComponentModel.DataAnnotations allows you to create new attribute and with the help of this you can validate the data as per your requirement.

How to Do

ValidationAttribute is abstract class and it is use as base class of various inbuilt validation attribute like required, stringlength, etc. With help of ValidationAttribute class we can create our own new validation attribute.

The following are the steps to create a new Validation.

Step 1: Create a class which inherits from ValidationAttribute:

public sealed class MyRequiredAttribute : ValidationAttribute
{
....
....
}

Step 2: The validation attribute class has a method called "IsValid" to validate data. If you want to do custom validation then you must override this method:

public sealed class MyRequiredAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var required = new RequiredAttribute();
        return required.IsValid(Convert.ToString(value).Trim());
    }
}


Example

In this article, I have created a new attribute, named "MyRequiredAttribute". Internally I have called the builtin attribute "RequiredAttribute", but instead of this you can write your custom code or logic to create a validation attribute.

I have also created another example to create a new attribute for Email. In the bottom of this attribute, I used "RegularExpressionAttribute" to validate the email address.

public sealed class EmailAttribute : ValidationAttribute
{

    public override bool IsValid(object value)
    {
        return new RegularExpressionAttribute(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$").IsValid(Convert.ToString(value).Trim());
    }
}

public class DataClass
{
    [Email]
    public string EmailAddress { get; set; }

    [MyRequiredAttribute(ErrorMessage = "Jignesh Test")]
    public string Password { get; set; }
}


Conclusion

System.ComponentModel.DataAnnotations allow us to create new validation attributes to write custom logic or code for validation. In MVC, creation of new attributes that are automatically picked up by the validation process of the DefaultModelBinder is easy.

Login to add your contents and source code to this article
post comment
     

Yes Gaurav. Its really good idea beacuse the Data Annotation validators is that they enable us to perform validation simply by adding one or more attributes like the Required or String Length attribute – on the class property. this will help to reduce code size as well as code reusability. Also MVC, EF and WCF inbuilt support for this.

Posted by Jignesh Trivedi Jun 28, 2012

Is Data Annotations really a good idea for validation?

Posted by Gaurav Gupta Jun 28, 2012
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.