2011-06-02 60 views
7

我正在使用DataAnnotations,jQuery.validate和jquery.validate.unobtrusive創建日期範圍驗證程序。我已經閱讀以下內容: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.htmljQuery.validator.unobtrusive.adapters.addMinMax往返,在MVC3中不起作用

http://weblogs.asp.net/mikaelsoderstrom/archive/2010/10/06/unobtrusive-validation-in-asp-net-mvc-3.aspx

等,但不能發佈它們(小白)

以及大部分崗位對SO。我巴寧我的頭靠在牆上,任何幫助可以用啤酒/食品/代碼/等被rewardde;)反正這裏是代碼:

我有以下的參數模型對象:

[Display(Name = "Start date"), 
DayRange(0, 5, ErrorMessage = "The Start Date must be between today and 5 days time.")] 
public DateTime StartDate { get; set; } 

DayRange是一個自定義屬性類:

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 
public class DayRangeAttribute : RangeAttribute, IClientValidatable 
{ 
    private int _minimumDays; 
    private int _maximumDays; 

    public DayRangeAttribute(int minimumDays, int maximumDays) : base(minimumDays, maximumDays) 
    { 
     _minimumDays = minimumDays; 
     _maximumDays = maximumDays; 
    } 

    public override bool IsValid(object value) 
    { 
     var dateToBeTested = value as DateTime?; 
     return dateToBeTested.HasValue && dateToBeTested.Value >= DateTime.Today.AddDays(_minimumDays) && dateToBeTested.Value <= DateTime.Today.AddDays(_maximumDays); 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     var rule = new ModelClientValidationRule 
         { 
          ErrorMessage = this.ErrorMessage, 
          ValidationType = "dayrange" 
         }; 
     rule.ValidationParameters.Add("min", _minimumDays); 
     rule.ValidationParameters.Add("max", _maximumDays); 
     yield return rule; 
    } 
} 

我在我的web.config以下:

<appSettings> 
    <add key="ClientValidationEnabled" value="true"/> 
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/> 
</appSettings> 

我已經有下列JS觸發前的文件準備就緒(試圖觸發它時,文檔準備好太):

jQuery.validator.addMethod('dayrange', function (value, element, param) { 
    if (!value) return false; 
    var now = Date(); 
    var dateValue = Date.parse(value); 
    var minDate = now.setDate(now.getDate() - param.min); 
    var maxDate = now.setDate(now.getDate() + param.max); 

    return this.optional(element) && dateValue >= minDate && dateValue <= maxDate; 
}, 'Must fall in range'); 

jQuery.validator.unobtrusive.adapters.addMinMax('dayrange', 'minlength', 'maxlength', 'dayrange'); 

我在做什麼錯?在此先感謝,Jol

回答

19

解決!我忘了/不明白你必須將jQuery本身傳遞給函數閉包。因此,在客戶端自定義驗證應該是這樣的:

$(function() { 
    jQuery.validator.addMethod('dayRange', function (value, element, param) { 
     if (!value) return false; 
     var valueDateParts = value.split(param.seperator); 
     var minDate = new Date(); 
     var maxDate = new Date(); 
     var now = new Date(); 
     var dateValue = new Date(valueDateParts[2], 
          (valueDateParts[1] - 1), 
          valueDateParts[0], 
          now.getHours(), 
          now.getMinutes(), 
          (now.getSeconds()+5)); 

     minDate.setDate(minDate.getDate() - parseInt(param.min)); 
     maxDate.setDate(maxDate.getDate() + parseInt(param.max)); 

    return dateValue >= minDate && dateValue <= maxDate; 
}); 

    jQuery.validator.unobtrusive.adapters.add('dayrange', ['min', 'max', 'dateseperator'], function (options) { 
     var params = { 
      min: options.params.min, 
      max: options.params.max, 
      seperator: options.params.dateseperator 
     }; 

     options.rules['dayRange'] = params; 
     if (options.message) { 
      options.messages['dayRange'] = options.message; 
     } 
    }); 
}(jQuery)); 

我也改變我的適配器添加到不顯眼的方式,所以我可以添加額外的屬性。切勿發送給服務器端開發人員做前端工程師的工作;)希望這可以幫助某人。

+1

幫了我!謝謝:-) – Peter 2011-06-27 08:59:02

+0

快樂伴侶。花了我幾個小時才發現'(jQuery)'最後失蹤了,希望你沒有花費太多時間。 – jolySoft 2011-06-27 11:01:49

+0

我一直在尋找如何使用jquery驗證來構建自定義驗證函數,您可以傳遞參數。你給了我一個很好的例子! – Peter 2011-06-27 13:08:24

2

參考: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

adapters.addMinMax()的參數是排序依據這樣的:

adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute 

,所以你需要這樣的:

jQuery.validator.unobtrusive.adapters.addMinMax('dayrange', '', '', 'dayrange','minlength', 'maxlength'); 

AND,,, 

param.min, param.max be sure to undefine. param is an purely array as: ['111','000']. 

,所以你需要:

var minDate = now.setDate(now.getDate() - param[0]); 
var maxDate = now.setDate(now.getDate() + param[1]);