今天应笑笑老师之问,做了一个模型验证的例子,发现之前对这个东西的理解太片面,重新整理了一下思路
字段验证优先级高于类验证
什么是类验证呢?就是两个字段组合的验证,比如你Admin不允许修改密码,你修改密码的Model在后端判断字段是不是Admin,并且密码的md5是不是特定的,我只是举例子啊,这样的验证,优先级是低于字段的验证的,字段验证通过,才会触发这个验证
验证的通用部分代码抄袭自刘总
刘总博客园链接附上https://www.cnblogs.com/lwc1st/
public class ModelStateResult{public bool IsValid { get; }public List<ValidationResult> ValitionResultList { get; }public ModelStateResult(bool isValid, List<ValidationResult> valitionResultList){IsValid = isValid;ValitionResultList = valitionResultList;}}public static class ValitionExtension{public static ModelStateResult Valition<TEntity>(this TEntity entity) where TEntity:class,new(){var valitionResultList = new List<ValidationResult>();var context = new ValidationContext(entity, null, null);var isValidate = Validator.TryValidateObject(entity, context, valitionResultList, true);return new ModelStateResult(isValidate, valitionResultList);}}
我们先写一个实体对象的常规验证
public class UserInfo{[Required]public string User { get; set; }[StringLength(32, MinimumLength = 10)]public string Password { get; set; }public string PhoneNumber { get; set; }}
验证部分代码附上
UserInfo testEntity = new UserInfo(){User = null,Password = "123",PhoneNumber = "123456"};var testResult = testEntity.Valition();
我们看看执行结果
我们再添加一个,判断是否Admin的验证
public class UserInfoValidation{public static ValidationResult IsAdmin(object value, ValidationContext validationContext){if (value is UserInfo userInfo){if (userInfo.User.Equals("Admin")){var isValidate = userInfo.Password.Equals("12345678901");if (!isValidate){return new ValidationResult("User Is Admin, Password Check Error");}}}return ValidationResult.Success;}}
在实体对象上打上CustomValidation特性,会提示是两个参数,第一个就是实现了自定义验证的类的Type,第二个参数是方法名
完整的实体对象代码为
[CustomValidation(typeof(UserInfoValidation), "IsAdmin")]public class UserInfo{[Required]public string User { get; set; }[StringLength(32, MinimumLength = 10)]public string Password { get; set; }public string PhoneNumber { get; set; }}
再写一个测试代码
var entity = new UserInfo(){User = "Admin",Password = "1234567890",PhoneNumber = "18382986022"};var validateResult = entity.Valition();
附上测试结果
特别注意一点,这个类的模型验证是低于字段的模型验证的,所以字段验证不通过,这里是不触发的,切记