推出自己的验证属性并不难。我前段时间实施了一个。它检查其他属性的值是否小于使用此属性修饰的属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited=true)]
public class SmallerThanAttribute : ValidationAttribute
{
public SmallerThanAttribute(string otherPropertyName)
{
this.OtherPropertyName = otherPropertyName;
}
public string OtherPropertyName { get; set; }
public string OtherPropertyDisplayName { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return IsValid(OtherPropertyName, value, validationContext);
}
private ValidationResult IsValid(string otherProperty, object value, ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectType.GetProperty(otherProperty);
if (otherPropertyInfo == null)
{
throw new Exception("Could not find property: " + otherProperty);
}
var displayAttribute = otherPropertyInfo.GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault() as DisplayAttribute;
if (displayAttribute != null && OtherPropertyDisplayName == null)
{
OtherPropertyDisplayName = displayAttribute.GetName();
}
object otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
var smaller = (IComparable) value;
var bigger = (IComparable) otherPropertyValue;
if (smaller == null || bigger == null)
{
return null;
}
if (smaller.CompareTo(bigger) > 0)
{
return new ValidationResult(string.Format(ValidatorResource.SmallerThan, validationContext.DisplayName, OtherPropertyDisplayName));
}
return null;
}
}
有一个问题。错误消息格式在资源类属性 (ValidatorResource.SmallerThan) 中定义,因此它不可插入——我不需要这个。但是,我认为这对您来说仍然是一个很好的起点。