大佬教程收集整理的这篇文章主要介绍了asp.net-mvc – 如何在RegularExpression中忽略大小写?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
using System.ComponentModel.DataAnnotations; public class File { ... [RegularExpression(@"([^.]+[.](jpg|jpeg|gif|png|wpf|doc|docx|xls|xLSX ...,Errormessage = "Invali File Name"] public String Name{ get; set; } ... }
有一个RegularExpressionValidator检查文件扩展名.
有没有一种快速的方法,我可以告诉它忽略扩展的情况,而不必明确地添加大写变体到我的验证表达式?
我需要这个用于服务器端和客户端的RegularExpressionValidator.
“(?i)”可以用于服务器端,但这并不适用于客户端
public class IgnorecaseRegularExpressionAttribute : RegularExpressionAttribute,IClientValidatable { public IgnorecaseRegularExpressionAttribute(String pattern): base("(?i)" + pattern) { } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,ControllerContext context) { var rule = new ModelClientValidationRule { ValidationType = "icregex",Errormessage = Errormessage }; // Remove the (?i) that we added in the pattern as this // is not necessary for the client validation rule.ValidationParameters.Add("pattern",Pattern.SubString(4)); yield return rule; } }
然后用它装饰你的模型:
[IgnorecaseRegularExpression(@"([^.]+[.](jpg|jpeg|gif|png|wpf|doc|docx|xls|xLSX",Errormessage = "Invalid File Name"] public String Name { get; set; }
最后在客户端上写一个适配器:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script> <script type="text/javascript"> jQuery.validator.unobtrusive.adapters.add('icregex',[ 'pattern' ],function (options) { options.rules['icregex'] = options.params; options.messages['icregex'] = options.message; }); jQuery.validator.addMethod('icregex',function (value,element,params) { var match; if (this.optional(element)) { return true; } match = new RegExp(params.pattern,'i').exec(value); return (match && (match.index === 0) && (match[0].length === value.length)); },''); </script> @using (Html.beginForm()) { @Html.EditorFor(x => x.Name) @Html.ValidationmessageFor(x => x.Name) <input type="submit" value="OK" /> }
当然,您可以将客户端规则外部化为单独的JavaScript文件,以便您无需在任何地方重复.
以上是大佬教程为你收集整理的asp.net-mvc – 如何在RegularExpression中忽略大小写?全部内容,希望文章能够帮你解决asp.net-mvc – 如何在RegularExpression中忽略大小写?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。