1.验证特性定义
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class CountryAttribute : ValidationAttribute { public string AllowCountry { get; set; } /// <summary> /// 验证数据是否合法 /// </summary> /// <param name="value"></param> /// <returns></returns> public override bool IsValid(object value) { return string.Equals(value, AllowCountry); } /// <summary> /// 验证结果 /// </summary> /// <param name="value"></param> /// <param name="validationContext"></param> /// <returns></returns> protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (string.Equals(value, AllowCountry)) return ValidationResult.Success; else return new ValidationResult(string.Format("{0}-{1}-{2} 字段非法", validationContext.DisplayName, validationContext.MemberName, ErrorMessage), new[] { validationContext.MemberName }); } }//end
2.类属性定义
public class test { /// <summary> /// 姓名1 /// </summary> [CountryAttribute(AllowCountry = "fhc", ErrorMessage = "自定义错误1"), Display(Name = "姓名")] public string name { set; get; } [CountryAttribute(AllowCountry = "fhc2", ErrorMessage = "自定义错误2"), Display(Name = "姓名2")] public string name2 { set; get; } [Range(10, 70, ErrorMessage = "自定义错误")] public int age { set; get; } }//end
3.验证结果方法
/// <summary> /// 错误列表 /// </summary> /// <param name="o"></param> /// <returns></returns> public List<string> ErrorList(object o) { List<string> list = new List<string>(); var context = new ValidationContext(o, null, null); var results = new List<ValidationResult>(); Validator.TryValidateObject(o, context, results, true); foreach (var validationResult in results) { list.Add(validationResult.ErrorMessage); } return list; }
4.实际使用
test t = new test() { age = 0, name = "fan" }; List<string> list = ErrorList(t);
如果list长度为0则表示没有错误,否则则是错误列表。