我已经编写了一个自定义属性,但它似乎不适用于客户端。它仅在我调用 ModelState.IsValid() 方法时在服务器上有效。我在网上某处读到我需要在应用程序启动方法上注册自定义属性,但不清楚。请帮忙。
public class MaximumAmountAttribute : ValidationAttribute
{
private static string defErrorMessage = "Amount available '$ {0:C}' can not be more than loan amount '$ {1:C}'";
private string MaximumAmountProperty { get; set; }
double minimumValue = 0;
double maximumValue = 0;
public MaximumAmountAttribute(string maxAmount)
: base(defErrorMessage)
{
if (string.IsNullOrEmpty(maxAmount))
throw new ArgumentNullException("maxAmount");
MaximumAmountProperty = maxAmount;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
PropertyInfo otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(MaximumAmountProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult(string.Format("Property '{0}' is undefined.", MaximumAmountProperty));
}
var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (otherPropertyValue != null && !string.IsNullOrEmpty(otherPropertyValue.ToString()))
{
minimumValue = Convert.ToDouble(value);
maximumValue = Convert.ToDouble(otherPropertyValue);
if (minimumValue > Convert.ToDouble(otherPropertyValue.ToString()))
{
return new ValidationResult(string.Format(defErrorMessage, minimumValue, maximumValue));
}
}
}
return ValidationResult.Success;
}
}