1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | publicclassBaseModel { publicboolValidate() { var result =true; foreach(var propertyinthis.GetType().GetProperties()) { foreach(var attributeinproperty.GetCustomAttributes(true)) { if(attributeisValidationAttribute) { try { var attr = (ValidationAttribute)attribute; result = result && attr.IsValid(property.GetValue(this,null)); } catch(Exception) { result =false; } } } } returnresult; } } |
1 2 3 4 5 | publicclassLoginModel : BaseModel { [UserNameValidation] publicstringUserName {get;set; } } |
1 2 3 4 5 6 7 8 | [System.AttributeUsage(System.AttributeTargets.Property)] publicclassValidationAttribute : Attribute { publicvirtualboolIsValid(objectobj) { returnfalse; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | publicclassUserNameValidationAttribute : ValidationAttribute { privateconststringUSER_NAME_REGEX =@"^\w+$"; publicoverrideboolIsValid(objectobj) { if(obj ==null) { returnfalse; } var value = objasstring; if(Regex.IsMatch(value, USER_NAME_REGEX)) { returntrue; } returnfalse; } } |
1 2 3 4 5 6 7 8 9 | classProgram { staticvoidMain(string[] args) { var loginModel =newLoginModel(); loginModel.UserName ="UserName"; Console.WriteLine(loginModel.Validate()); } } |