asp.net-mvc – ASP.NET MVC:添加将DisplayName合并到自定义ValidationAttr
发布时间:2020-10-19 18:18:14 所属栏目:asp.Net 来源:互联网
导读:我正在使用带有DataAnnotations的ASP.NET MVC.我创建了以下自定义ValidationAttribute,它可以正常工作. public class StringRangeAttribute : ValidationAttribute{ public int MinLength { get; set; } public int MaxLength { get
我正在使用带有DataAnnotations的ASP.NET MVC.我创建了以下自定义ValidationAttribute,它可以正常工作. public class StringRangeAttribute : ValidationAttribute { public int MinLength { get; set; } public int MaxLength { get; set; } public StringRangeAttribute(int minLength,int maxLength) { this.MinLength = (minLength < 0) ? 0 : minLength; this.MaxLength = (maxLength < 0) ? 0 : maxLength; } public override bool IsValid(object value) { //null or empty is <em>not</em> invalid string str = (string)value; if (string.IsNullOrEmpty(str)) return true; return (str.Length >= this.MinLength && str.Length <= this.MaxLength); } } 但是,出现的错误消息是标准的“字段*无效”.我想将其更改为:“[DisplayName]必须介于[minlength]和[maxlength]之间”,但我无法弄清楚如何从此类中获取DisplayName甚至字段的名称. 谁知道? 解决方法稍微修改过的StringLengthAttribute:public class StringRangeAttribute : ValidationAttribute { // Methods public StringRangeAttribute(int minimumLength,int maximumLength) : base(() => "The {0} must be between {1} and {2} chars long.") { MaximumLength = maximumLength; MinimumLength = minimumLength; } public override string FormatErrorMessage(string name) { return string.Format(CultureInfo.CurrentCulture,ErrorMessageString,new object[] { name,MinimumLength,MaximumLength }); } public override bool IsValid(object value) { if (value != null) { return (((string)value).Length <= MaximumLength) && (((string)value).Length >= MinimumLength); } return true; } public int MaximumLength { get; set; } public int MinimumLength { get; set; } } (编辑:岳阳站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-ajax – Ajax脚本管理器和母版页
- 如何在ASP.NET Web应用程序中打开一个SectionGroup?
- asp.net中MVC借助Iframe实现无刷新上传文件实例
- 如何从经典ASP输出Excel * .xls文件
- asp.net – 是否可以根据用户角色隐藏/显示Kendo网格列?
- 在ASP.NET MVC4中是否可以将C#或VB函数标记为Javascript?
- asp.net-mvc-3 – MVC 3不显眼的验证 – 有条件地禁用/启用
- asp.net – 登录后对Membership.GetAllUsers()的例外情况:
- 隐藏ASP.NET菜单项
- asp.net-mvc – 构建视图模型的最佳方法是什么?
推荐文章
站长推荐
- Asp.NET控制文件上传的大小方法(超简单)
- asp.net – VB.NET – 如何使用Active Directory
- ASP.NET虚拟路径映射到另一个不允许的应用程序
- asp.net-mvc – 缩小ASP.NET MVC中的Action Filt
- ASP.NET设计网络硬盘之删除文件夹实现代码
- asp.net – Isapi过滤器无法在IIS 7上运行(在IIS
- asp.net – Session Timeout .NET
- asp.net-mvc – 在一个页面中以两种不同的形式使
- 在MVC中使用Json.Net序列化和反序列化Json对象
- 我如何让Fiddler捕获我的MVC应用程序向我的ASP.N
热点阅读