自定义验证规则ValidationAttribute的使用
概述
大家在做項(xiàng)目的時(shí)候,在實(shí)體類上添加一些特性,可以實(shí)現(xiàn)后端實(shí)體的數(shù)據(jù)校驗(yàn)。有時(shí)候,可能需要自定義驗(yàn)證屬性。實(shí)現(xiàn)原理:利用反射獲取實(shí)體的每一個(gè)屬性,并通過屬性獲取屬性上標(biāo)注的特性,調(diào)用特性的Validate方法(此方法自定義的)來驗(yàn)證屬性的值是否合法。
代碼實(shí)現(xiàn)
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?(複寫預(yù)設(shè)的錯(cuò)誤訊息)CustomerValidation.RegisterCustomerValidation();DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomizedRequired),?typeof(RequiredAttributeAdapter));DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CustomizedStringLength),?typeof(StringLengthAttributeAdapter));3、在字段調(diào)用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、控制器上驗(yàn)證ModelState.IsValid
??if?(!ModelState.IsValid){Response.Redirect(Request.Url.AbsolutePath);Response.End();return;}當(dāng)我們通過繼承ValidationAttribute創(chuàng)建我們自己的驗(yàn)證特性的時(shí)候,可以通過重寫公有方法IsValid或者受保護(hù)方法IsValid來實(shí)現(xiàn)我們自定義的驗(yàn)證邏輯。我們之所以能夠通過重寫任一個(gè)IsValid方法是我們自定義驗(yàn)證邏輯生效的原因在于這兩個(gè)方法在ValidationAttribute特殊的定義方法。
總結(jié)
以上是生活随笔為你收集整理的自定义验证规则ValidationAttribute的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 动手造轮子:实现一个简单的基于 Cons
- 下一篇: 云原生 | 阿里巴巴的Dapr实践与探索