2013-03-27 128 views
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; 
    } 
} 

回答

2

創建服務器端驗證不「trasnfer」驗證規則給客戶端瀏覽器(呈現自定義JavaScript驗證功能)。
您也必須將驗證邏輯寫爲客戶端腳本。有一些事情,你必須做到:

  1. 確保要素(輸入)具有客戶端上進行驗證看起來像這樣:

    <input data-val-MaximumAmount="Validation error massage" />

    數據-VAL-XXX需要保存錯誤消息的屬性。 Html.TextBoxFor也是這樣做的(將這些屬性添加到呈現的html元素中)。

  2. 您必須創建和註冊客戶端驗證這種方式:

    (function ($) { 
        // Creating the validation method 
        $.validator.addMethod('MaximumAmount', function (value, element, param) { 
         if (...) // some rule. HERE THE VALIDATION LOGIC MUST BE IMPLEMENTED! 
          return false; 
         else 
          return true; 
        }); 
    
        // Registering the adapter 
        $.validator.unobtrusive.adapters.add('MaximumAmount', function (options) { 
         var element = options.element, 
          message = options.message; 
    
         options.rules['MaximumAmount'] = $(element).attr('data-val-MaximumAmount'); 
         if (options.message) { 
          options.messages['MaximumAmount'] = options.message; 
         } 
        }); 
    
    })(jQuery); 
    
    // Binding elements to validators 
    $(function() { 
        $(':input[data-val-MaximumAmount]').each(function() { 
         $.validator.unobtrusive.parseElement(this, true); 
        }); 
    }); 
    
+0

@bugarist - 嗨,你的解決方案是工作,但我在使用的驗證消息的問題。我確實提供了屬性的驗證消息,但它說我收到的消息是「警告:沒有爲金額定義的消息」。金額是我正在驗證的財產。 – CodeNoob 2013-03-27 13:54:11

+0

請檢查您的代碼中是否使用了與上述相同的名稱作爲驗證規則。特別是檢查這一行 - 'options.messages ['MaximumAmount'] = options.message;'。檢查我在任何地方使用了相同的字符串'MaximumAmount' – bugartist 2013-03-27 14:29:05

+1

@bugarist,哇感謝的人。我希望我能給你買一杯飲料。我在options.messages []上留下了's'。 – CodeNoob 2013-03-27 14:58:57