我有以下 ValidationAttribute 类
[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;
}
...
...
}
它在构造函数中有两个日期属性名称和一个运算符。
在验证方法中,返回语句 LeftDate Operator RightDate 的结果。
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;
}
}
因为这是一个 AttriuteTargets.Class 属性,所以我知道框架不可能知道导致验证失败的属性。但我知道是左日期属性失败了,因此我想将模型状态中错误的 ID 设置为此属性。这样做的原因是我希望在表单中标记失败的字段。
问题:如何修改ModelState中添加到错误集合中的错误项,使其id对应于表单中的特定字段?