自定义验证规则ValidationAttribute的使用
生活随笔
收集整理的這篇文章主要介紹了
自定义验证规则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的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 动手造轮子:实现一个简单的基于 Cons
- 下一篇: 云原生 | 阿里巴巴的Dapr实践与探索