【发布时间】:2016-02-17 16:32:29
【问题描述】:
我正在编写一个自定义属性来验证名字和姓氏不超过一定数量的字符,但错误消息没有像开箱即用注释那样显示。
这是我的实现。
public class User
{
[Required(ErrorMessage = "Last Name is required.")]
[RegularExpression(@"^[a-zA-Z'\s]{1,50}$", ErrorMessage = "Please enter a valid last name.")]
[FullNameMaxLength("FirstName")]
public string LastName { get; set; }
}
public class FullNameMaxLengthAttribute : ValidationAttribute
{
private string _firstName;
public FullNameMaxLengthAttribute(string firstName)
{
_firstName = firstName;
}
protected override ValidationResult IsValid(object lastName, ValidationContext validationContext)
{
clsUserRegistration userRegistrationContext = (clsUserRegistration)validationContext.ObjectInstance;
if (lastName != null)
{
string strValue = lastName.ToString();
PropertyInfo propInfo = validationContext.ObjectType.GetProperty(_firstName);
if (propInfo == null)
return new ValidationResult(String.Format("Property {0} is undefined.", _firstName));
var fieldValue = propInfo.GetValue(validationContext.ObjectInstance, null).ToString();
if (strValue.Length + fieldValue.Length > 53)
{
return new ValidationResult("First and last names are too long!");
}
return ValidationResult.Success;
}
return null;
}
}
在我看来,我有一个 ValidationMessageFor,它适用于非自定义属性。当我单步执行我的模型时,它会返回 ValidationMessage,但我看不到该错误消息。有什么想法吗?
【问题讨论】:
-
我假设您的问题是它在提交或发布之前没有进行验证,但是一旦它进入服务器并返回,就会显示错误消息。原因是您必须在提交之前添加 javascript 来处理客户端处理。这是一篇应该让你走上正轨的文章devtrends.co.uk/blog/…
标签: asp.net-mvc