如何使用动态模式从模型属性创建regularExpressionAttributepublicclassCity{[DynamicRequularExpressionAttribute(PatternProperty="RegEx")]publicstringZip{get;设置;}公共字符串正则表达式{得到;set;}}我想创建这个属性,其中模式来自其他属性,而不是像原始RegularExpressionAttribute那样声明为静态。任何想法都会不胜感激–谢谢线条之间的某些东西应符合要求:publicclassDynamicRegularExpressionAttribute:ValidationAttribute{publicstringPatternProperty{get;放;}protectedoverrideValidationResultIsValid(objectvalue,ValidationContextvalidationContext){PropertyInfoproperty=validationContext.ObjectType.GetProperty(PatternProperty);if(property==null){returnnewValidationResult(string.Format("{0}isunknownproperty",PatternProperty));}varpattern=property.GetValue(validationContext.ObjectInstance,null)asstring;if(string.IsNullOrEmpty(pattern)){returnnewValidationResult(string.Format("{0}必须是一个有效的字符串正则表达式",PatternProperty));}varstr=字符串形式的值;if(string.IsNullOrEmpty(str)){//我们认为空字符串对该属性有效//如果不是这种情况,则用[Required]修饰returnnull;}varmatch=Regex.Match(str,pattern);如果(!match.Success){返回新的ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));}返回空值;}}然后:模型:publicclassCity{[DynamicRegularExpression(PatternProperty="RegEx")]publicstringZip{get;放;}publicstringRegEx{get;放;}}控制器:publicclassHomeController:Controller{publicActionResultIndex(){varcity=newCity{RegEx="[0-9]{5}"};返回视图(城市);}[HttpPost]publicActionResultIndex(Citycity){returnView(city);}}查看:@modelCity@using(Html.BeginForm()){@Html.HiddenFor(x=>x.RegEx)@Html.LabelFor(x=>x.Zip)@Html.EditorFor(x=>x.Zip)@Html.ValidationMessageFor(x=>x.Zip)}覆盖以ValidationContext为参数的Validate方法,使用ValidationContext从相关属性中获取正则表达式字符串并应用正则表达式,返回匹配value以上就是C#学习教程:HowtousedynamicmodetocreateregularExpressionAttributemodel属性分享的所有内容,如果对大家有用,需要详细了解C#学习教程,希望大家多多关注——本文章来自网络收藏,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
