asp.net mvc 3 - jQuery.validator.unobtrusive.adapters.addMinMax 往返,在 MVC3 中不起作用



我正在使用DataAnnotations、jQuery.validate和jQuery.validate.uno唐突创建一个日范围验证器。我已经阅读了以下内容:http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

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

和其他但不能张贴它们(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

已解决!我忘了/不明白您必须将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));

我还将添加适配器的方式更改为不引人注目,这样我就可以添加其他属性。永远不要发送给服务器端开发人员来做前端工程师的工作;)希望这能帮助到别人。

参考: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]);

相关内容

  • 没有找到相关文章

最新更新