C# 实体model验证输出
新建Model实体:
[Required(ErrorMessage = @"地址 1 为必填项!")] [StringLength(99, ErrorMessage = @"地址 1 不能超过99个字符")] public string Address1 { get; set; }
给实体赋值判断输出:
var model = new ClassModel { Address1 = "", }; var errors = new List<ValidationResult>(); var context = new ValidationContext(model, null, null); Validator.TryValidateObject(model, context, errors, true); if (errors.Any()) { MessageBox.Show(errors.Select(t => t.ErrorMessage).FirstOrDefault()); }