Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

CustomValidation Attribute - ASP.NET

RSS
Modified on Tue, Sep 11, 2012, 7:53 AM by Administrator Categorized as ASP·NET MVC, ASP·NET Web Forms

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);
    }

}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.