本文介绍了jQuery.validator.unobtrusive.adapters.addMinMax往返,不MVC3工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建使用DataAnnotations,jQuery.validate和jquery.validate.unobtrusive每天范围验证。我已经阅读以下内容:
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

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)

以及大部分的职位上左右。我巴宁我的头靠在墙上,任何帮助可以与啤酒/食品/ code /等被rewardde;)无论如何,这里的code:

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是一个自定义属性类:

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

我在我的web.config以下内容:

I have the following in my web.config:

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

我有以下有JS触发前的文件准备就绪(试图触发它时,文档准备过):

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

推荐答案

解决了!我忘了/不明白,你必须自己的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.

这篇关于jQuery.validator.unobtrusive.adapters.addMinMax往返,不MVC3工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 13:50