我正在使用DataAnnotations,jQuery.validate和jquery.validate.unobtrusive創建日期範圍驗證程序。我已經閱讀以下內容: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.htmljQuery.validator.unobtrusive.adapters.addMinMax往返,在MVC3中不起作用
等,但不能發佈它們(小白)
以及大部分崗位對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
幫了我!謝謝:-) – Peter 2011-06-27 08:59:02
快樂伴侶。花了我幾個小時才發現'(jQuery)'最後失蹤了,希望你沒有花費太多時間。 – jolySoft 2011-06-27 11:01:49
我一直在尋找如何使用jquery驗證來構建自定義驗證函數,您可以傳遞參數。你給了我一個很好的例子! – Peter 2011-06-27 13:08:24