.NET MVC2如何在使用自定义验证attribute时向ModelState添加错误
-
01-10-2019 - |
题
我有以下验证课程
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class DateValidationAttribute : ValidationAttribute
{
public DateValidationAttribute(string leftDateProperty, CompareOperator compareOperator, string rightDateProperty, string errorMessage)
: base(errorMessage)
{
LeftDateProperty = leftDateProperty;
Operator = compareOperator;
RightDateProperty = rightDateProperty;
}
...
...
}
它在构造函数中需要两个日期属性名称和一个操作员。
在验证方法中,返回语句左转操作员右日期的结果。
public override bool IsValid(object value)
{
DateTime leftDate;
DateTime rightDate;
// Get all properties on the view model
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
DateTime rightDate = (DateTime)properties.Find(RightDateProperty, true).GetValue(value);
DateTime leftDate = (DateTime)properties.Find(LeftDateProperty, true).GetValue(value);
// Perform rule check
switch (Operator)
{
case CompareOperator.Equal:
return leftDate.Equals(rightDate);
case CompareOperator.Greater:
return leftDate > rightDate;
case CompareOperator.Lesser:
return leftDate < rightDate;
case CompareOperator.GreaterOrEqual:
return leftDate >= rightDate;
case CompareOperator.LesserOrEqual:
return leftDate <= rightDate;
default:
return false;
}
}
因为这是一个attriutetarget.class属性,所以我知道该框架不可能知道导致验证失败的属性。但是我知道它是失败的日期属性,因此我想将ModelState中错误的ID设置为此属性。原因是我希望以形式标记失败字段。
问题: 如何修改ModelState中添加到错误集合中的错误项,以使其ID与表单中的特定字段相对应?
解决方案
我找到了使用idataErrorinfo这样做的更好的方法
这就是我的做法。这不是一个通用的问题。使用此解决方案,您必须每张支票进行编码。但是现在,该验证将一直保持在JavaScript并突出显示失败输入元素的过程中。
public class TestModel: IDataErrorInfo
{
public TestModel()
{
}
[Required]
public string StartDate { get; set; }
[Required]
public string EndDate { get; set; }
#region IDataErrorInfo Members
public string Error
{
get
{
return string.Empty;
}
}
public string this[string columnName]
{
get
{
switch (columnName)
{
case "StartDate":
{
if (StartDate < DateTime.Today)
{
return "Start date must not be a date in the past";
}
break;
}
case "EndDate":
{
if (EndDate < StartDate)
{
return "End date must not be a date before start date";
}
break;
}
default:
return string.Empty;
}
return string.Empty;
}
}
}
不隶属于 StackOverflow