asp.net-mvc – ASP.NET MVC:添加将DisplayName合并到自定义ValidationAttr
发布时间:2020-10-19 11:43:52 所属栏目: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-mvc – ViewModels和渲染
- asp.net 使用驻留在页面中的Cache缓存常用可定时更新的数据
- asp.net-mvc – 如何在asp.net mvc3项目中开始使用openID?
- 在MVC中使用Json.Net序列化和反序列化Json对象
- ASP.NET中的应用程序生存期
- asp.net – 是否有可能过滤SignalR中的接收器?
- 从Asp.Net MVC 6 API返回JSON错误
- .net – 加密ApplicationServices ConnectionString
- asp.net-mvc-3 – 在F#中的ViewBag动态对象上设置属性
- 具有多个ASP.NET Web应用程序的Visual Studio解决方案
推荐文章
站长推荐
- asp.net-mvc – DropDownListFor在编辑视图上不重
- asp.net-mvc – 获取ControllerName和ActionName
- asp.net-mvc-3 – Orchard CMS DataAnnotations
- asp.net-core – 加密ASP.Net Core中的连接字符串
- asp.net-mvc – 如何在ASP.NET MVC4中使用具有唯
- asp.net-mvc – 使用ASP.NET MVC进行项目组织的最
- Asp.Net超大文件上传问题解决
- asp.net-mvc-3 – MVC3,多文件上传,模型绑定
- asp.net – 我应该在Web应用程序中嵌入CSS / Jav
- asp.net – .NET Web API 2 OWIN承载令牌认证
热点阅读
