jQuery.validator.unobtrusive.adapters.addMinMax 往返,在 MVC3 中不起作用

发布于 2024-11-10 23:32:11 字数 2906 浏览 0 评论 0原文

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

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

等但不能发布它们(菜鸟)

以及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');

我做错了什么?预先感谢,乔尔

I am creating a day range validator using DataAnnotations, jQuery.validate and jquery.validate.unobtrusive. I've already read the following:
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

and other but can't post them (noob)

As well as most of the post on SO. I'm baning my head against a wall, any help could be rewardde with beer/food/code/etc ;) Anyway here's the code:

I have a model object with the following parameter:

[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 is a custom attribute class :

[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;
    }
}

I have the following in my web.config:

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

I have have following JS trigger before the document is ready (have tried triggering it when the doc is ready too ):

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');

What am I doing wrong? Thanks in advance, Jol

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

余厌 2024-11-17 23:32:11

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

我还更改了将适配器添加为不显眼的方式,以便我可以添加其他属性。永远不要发送给服务器端开发人员来做前端工程师的工作;)希望这对某人有帮助。

Solved! I forgot/didn't understand that you have to pass jQuery itself into the function closure. Therefore the custom validator on the client side should look like this:

$(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));

I also change the way I add the adapter to unobtrusive so I can add additional properties. Never send to server-side dev to do a front-end engineers job ;) Hope this helps someone.

烧了回忆取暖 2024-11-17 23:32:11

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

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

adapters.addMinMax()'s param is orderby this:

adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute

so you need this:

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'].

so you need:

var minDate = now.setDate(now.getDate() - param[0]);
var maxDate = now.setDate(now.getDate() + param[1]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文