public class MaxWordsAttribute: ValidationAttribute { private readonly int _maxMords; public MaxWordsAttribute(int maxMords):base("{0} has too many words") { this._maxMords = maxMords; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value!=null) { var valueAsString = value.ToString(); if (valueAsString.Split(' ').Length>_maxMords) { var errorMessage = FormatErrorMessage(validationContext.DisplayName); return new ValidationResult(errorMessage); } } return ValidationResult.Success; } }
validationContext 需要验证的内容
validationContext.DisplayName 验证属性的名字