我正在使用DataAnnotations创建一个日期范围验证器,jQuery.validate和jquery.validate.unobtrusive。我已经阅读了以下内容: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
和其他但不能发布(noob)
以及SO上的大多数帖子。我正在把头靠在墙上,任何帮助都可以用啤酒/食物/代码/等奖励;)无论如何,这里是代码:
我有一个带有以下参数的模型对象:
[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
答案 0 :(得分: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 :(得分: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]);