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

Page History: CustomValidation Attribute - ASP.NET

Compare Page Revisions



« Older Revision - Back to Page History - Current Revision


Page Revision: Tue, Sep 11, 2012, 7:51 AM


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 ClaimCheckRequestViewModelValidator
{
    public static ValidationResult ValidateZipCode(string input)
    {
        return ValidationProvider.ValidateZipCodeExt(input, "Vendor ZIP code");
    }
}

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

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

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

        if (mc.Count == 1)
            return DA.ValidationResult.Success;
        else
            return new DA.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.