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