Reader Level:
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.
  • 1
  • 0
  • 20746
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.

COMMENT USING

Trending up