CustomValidation Attribute - ASP.NET

Overview

This article outlines how to implement the CustomValidation attribute on a view model.

Walk-Through

using System.ComponentModel.DataAnnotations;
. . .
[CustomValidation(typeof(MyViewModelValidator), "ValidateZipCode")]
public string ZipCode { get; set; }

public class MyViewModelValidator
{
    public static ValidationResult ValidateZipCode(string input)
    {
        return ValidationProvider.ValidateZipCodeExt(input, "ZIP code");
    }
}

public class ValidationProvider
{
    //== ZIP Code =============================================================================
    public static ValidationResult ValidateZipCodeExt(string zipCode, string fieldName)
    {
        string pattern = @"^\d{5}";
        return ValidateViaRegex(fieldName, zipCode, pattern);
    }

    //== Private Functions ====================================================================
    private static ValidationResult ValidateViaRegex(string fieldName, string fieldValue,
        string pattern)
    {
        if (fieldValue == null)
            return ValidationResult.Success;

        Regex regex = new Regex(pattern);
        MatchCollection mc = regex.Matches(fieldValue);

        if (mc.Count == 1)
            return ValidationResult.Success;
        else
            return new ValidationResult("'" + fieldValue + "' is not a valid " + 
                fieldName);
    }

}