买空间的网站,品牌网络推广方案,前台登录wordpress,建材网站建设方案概述大家在做项目的时候#xff0c;在实体类上添加一些特性,可以实现后端实体的数据校验。有时候#xff0c;可能需要自定义验证属性。实现原理#xff1a;利用反射获取实体的每一个属性#xff0c;并通过属性获取属性上标注的特性#xff0c;调用特性的Validate方法… 概述大家在做项目的时候在实体类上添加一些特性,可以实现后端实体的数据校验。有时候可能需要自定义验证属性。实现原理利用反射获取实体的每一个属性并通过属性获取属性上标注的特性调用特性的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特殊的定义方法。