Simple Custom Validation Attributes

Last week I did an overview of  Data Annotations. This week I am going to expand on data annotations by giving an example of a very simple custom validation attribute.

Sticking with my contact application theme lets say that I only wanted to allow contacts from a very small list of countries. The .Net framework does not have a built in validation attribute to cover this scenario which means I would need to create my own custom validation attribute to fill this need.

To create a custom validation attribute all you need is a class that inherits from ValidationAttribute and overrides the IsValid function.

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

public class ValidCountry : ValidationAttribute
{
    private readonly List<string> validCountries = new List<string>
    {
        "USA",
        "Canada",
        "Mexico"
    }; 

    public override bool IsValid(object value)
    {
        return value != null &&
               !validCountries.Contains((string)value);
    }
}

When validation for a property is performed the IsValid function of all the property’s validation attributes are run. The IsValid function is called with the value of the property being validated which will have to be cast to the type needed for validation. In my country example value is being cast to string and used see if the value is found in a list of valid countries.

Any property with the ValidCountry attribute would not validate unless the property was set to USA, Canada or Mexico. This is a contrived example, but it does give you an idea of how easy it is to add your own custom validation attributes.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.