1
我已经写了一个自定义属性,但它似乎不工作的客户端。它只在我调用ModelState.IsValid()方法时才起作用。我在网上读了一些地方,我需要在应用程序启动方法上注册自定义属性,但它并不清楚。请帮忙。与自定义验证属性如何获得自定义mvc3属性来验证客户端
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;
}
}
@bugarist - 嗨,你的解决方案是工作,但我在使用的验证消息的问题。我确实提供了属性的验证消息,但它说我收到的消息是“警告:没有为金额定义的消息”。金额是我正在验证的财产。 – CodeNoob 2013-03-27 13:54:11
请检查您的代码中是否使用了与上述相同的名称作为验证规则。特别是检查这一行 - 'options.messages ['MaximumAmount'] = options.message;'。检查我在任何地方使用了相同的字符串'MaximumAmount' – bugartist 2013-03-27 14:29:05
@bugarist,哇感谢的人。我希望我能给你买一杯饮料。我在options.messages []上留下了's'。 – CodeNoob 2013-03-27 14:58:57