欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

自定义验证规则ValidationAttribute的使用

发布时间:2023/12/4 编程问答 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 自定义验证规则ValidationAttribute的使用 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

概述

大家在做项目的时候,在实体类上添加一些特性,可以实现后端实体的数据校验。有时候,可能需要自定义验证属性。实现原理:利用反射获取实体的每一个属性,并通过属性获取属性上标注的特性,调用特性的Validate方法(此方法自定义的)来验证属性的值是否合法。

代码实现

1、自定义CustomizedStringLength,继承StringLengthAttribute

 public class CustomizedStringLength : StringLengthAttribute{private Type resourceType;private string resourceName;public CustomizedStringLength(int MaximumLength, Type ResourceType, string ResourceName) : base(MaximumLength){resourceType = ResourceType;resourceName = ResourceName;}public CustomizedStringLength(int MaximumLength) : base(MaximumLength){}public override string FormatErrorMessage(string name){string fieldName = resourceType.GetProperty(resourceName).GetValue(resourceType).ToString();if (MinimumLength != 0){this.ErrorMessage = string.Format(PageValidation.LimitLength, fieldName, MaximumLength, MinimumLength);}else{this.ErrorMessage = string.Format(PageValidation.StringMaxLengthTemplate, fieldName, MaximumLength);}return base.FormatErrorMessage(name);}} }

2、Application_Start全局注册

  //在 Controller 之前對 Model 做處理(字串 Trim)ModelBinders.Binders.DefaultBinder = new BQoolModelBinder();//註冊自訂的 Validation (複寫預設的錯誤訊息)CustomerValidation.RegisterCustomerValidation();DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomizedRequired), typeof(RequiredAttributeAdapter));DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomizedStringLength), typeof(StringLengthAttributeAdapter));

3、在字段调用CustomizedStringLength

    [CustomizedRequired(ResourceType: typeof(AccountSettingsElement), ResourceName: "AccountEmail")][CustomizedStringLength(100, ResourceType: typeof(AccountSettingsElement), ResourceName: "AccountEmail")][CustomizedRegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$", ResourceType: typeof(AccountSettingsElement), ResourceName: "AccountEmail")][Display(ResourceType = typeof(AccountSettingsElement), Name = "AccountEmail")]public string AccountEmail { get; set; }

4、控制器上验证ModelState.IsValid

  if (!ModelState.IsValid){Response.Redirect(Request.Url.AbsolutePath);Response.End();return;}

当我们通过继承ValidationAttribute创建我们自己的验证特性的时候,可以通过重写公有方法IsValid或者受保护方法IsValid来实现我们自定义的验证逻辑。我们之所以能够通过重写任一个IsValid方法是我们自定义验证逻辑生效的原因在于这两个方法在ValidationAttribute特殊的定义方法。

总结

以上是生活随笔为你收集整理的自定义验证规则ValidationAttribute的使用的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。