MaxWordsAttribute.cs
/* 自定义注解 */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace MusicStore.Models { /// <summary> /// 自定义最大单词注解 /// </summary> public class MaxWordsAttribute : ValidationAttribute { private readonly int _maxWords;//最大单词数量 public MaxWordsAttribute(int maxWords) : base("{0} has to many words.")//默认显示的提示消息 { this._maxWords = maxWords; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) { var valueAsString = value.ToString(); if (valueAsString.Split(' ').Length > _maxWords) { var errorMessage = FormatErrorMessage(validationContext.DisplayName);//替换值占位符,显示属性显示的名称 return new ValidationResult(errorMessage);//返回提示消息,如果用户有定义就取用户定义的,如果没定义就取默认的值 } } return ValidationResult.Success; } } }
/// <summary>
/// 我的单词
/// </summary>
[MaxWords(10,ErrorMessage="{0}已超过最大单词")]
public string MyWords { get; set; }
模型自身验证的实现
TestSelfValidating.cs
/* 练习自身模型对象 */ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace MusicStore.Models { public class TestSelfValidating:IValidatableObject { public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)//公开枚举对象 { if (Name != null && Name.Length > 10) { yield return new ValidationResult("The last name has too many words!", new[] { "Name" });//迭代对个返回枚举值,之所以要用迭代返回多个,因为自身验证是整个模型,所以要返回多个提示消息,后面要跟一个数组,因为可能会包含多个名称 } } public string Name { get; set; } } }
这样子就能实现自我验证了。