asp.net-mvc – ASP.NET MVC:添加将DisplayName合并到自定义ValidationAttr
发布时间:2020-10-19 09:41:54 所属栏目: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 Web应用程序安全性不适用于IIS 7?
- asp.net-mvc – System.Web.Mvc.WebViewPage.Model.get返回
- asp.net – 如何在MVC 3中设置图表系列颜色?
- asp.net – 干净的方式来防止输入按钮提交表单
- asp.net-mvc – ASP.NET MVC 2预览2:区域重复控制器问题
- asp.net – Lucene.Net和孵化状态
- asp.net – (客户端)禁用提交按钮的最佳方法是什么?
- asp.net – 如何在Visual Studio中添加NUnit
- asp.net-mvc – 是否有一个ASP MVC与JSTL标签等效?
- WPF 一个数据库连接测试的实现
推荐文章
站长推荐
- ASP.NET core Web中使用appsettings.json配置文件
- asp.net-mvc-3 – 从自定义授权属性访问角色
- asp.net-mvc – 使用AWS .NET SDK进行SNS订阅确认
- asp.net-mvc – URL中的ASP.NET MVC冒号
- ASP.NET Core中实现用户登录验证的最低配置示例代
- asp.net-mvc – 在没有模型的情况下手动将验证添
- 发布一款层次下拉列表控件
- ASP.NET中读取XML文件信息的4种方法与示例代码
- dependency-injection – 从ILogger访问当前的Ht
- asp.net – Windows应用程序与Web应用程序开发
热点阅读
