asp.net-mvc – ASP.NET MVC:添加将DisplayName合并到自定义Val
发布时间:2020-12-15 20:40:37 所属栏目:asp.Net 来源:网络整理
导读:我正在使用带有DataAnnotations的ASP.NET MVC.我创建了以下自定义ValidationAttribute,它可以正常工作. public class StringRangeAttribute : ValidationAttribute{ public int MinLength { get; set; } public int MaxLength { get; set; } public StringRa
我正在使用带有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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- .net – CS0012:类型’System.Data.Linq.DataContext’在未
- .net-4.0 – 从3.5升级到ASP.net 4.0后登录失败
- ASP.NET 2.0异步用户控件不起作用
- asp.net-mvc – 在MVC3中渲染导航
- asp.net-mvc – Razor中的条件链接
- asp.net – ‘NETCore.App’,版本’1.0.0-rc2-3002702’未找
- asp.net – 当用户使表单失效时,如何点击取消按钮时,如何清
- asp.net-mvc – 在MVC中处理重复表单的最佳方法是什么?
- asp.net-web-api – Web API 2 OWIN承载令牌认证 – Access
- Asp.Net Mvc突出显示当前页面链接技术?
推荐文章
站长推荐
- asp.net – 无法加载文件或程序集“Oracle.DataA
- asp.net-mvc – ASP.NET MVC Gotcha?失意
- asp.net-mvc – ASP.NET MVC SiteMap提供程序 –
- asp.net – 我可以在服务器端调用CustomValidato
- asp.net – SeriesChartType(枚举)示例
- asp.net-core – 具有不同root的ASP.Net核心反向
- asp.net – webservice和web应用程序有什么区别?
- ASP.NET:如何处理并行请求
- asp.net – 如何使用多个项目部署单个解决方案?
- asp.net-core – .net核心自定义身份验证中的Use
热点阅读