CustomValidation
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.