jQuery Chrome 中的非侵入式验证不会使用 dd/mm/yyyy 进行验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6906725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:32:25  来源:igfitidea点击:

Unobtrusive validation in Chrome won't validate with dd/mm/yyyy

jqueryjquery-uijquery-validatedatepickerunobtrusive-validation

提问by sipwiz

I'm trying to use the simplest possible scenario using a date picker in different browsers. I suspect I'm doing something very simple the wrong way but after lots of searching around I still haven't found a solution. Below is some sample code that represents what I'm attempting.

我正在尝试使用在不同浏览器中使用日期选择器的最简单的场景。我怀疑我正在以错误的方式做一些非常简单的事情,但是经过大量搜索后,我仍然没有找到解决方案。下面是一些代表我正在尝试的示例代码。

If I use Chrome (v12.0.742.122) and pick a date from the picker like 13/08/2011 the jQuery validation logic will not allow the page to submit even though I've explicitly specified the format as 'dd/mm/yy'.

如果我使用 Chrome (v12.0.742.122) 并从选择器中选择一个日期,例如 13/08/2011,jQuery 验证逻辑将不允许页面提交,即使我已明确指定格式为 'dd/mm/ YY'。

If I change the format to 'dd/M/yy' and choose a date like 13/Aug/2011 it works in Chrome but then won't submit for me in IE (v8.0.7600.16385). In FireFox (v3.6.18) both formats work.

如果我将格式更改为“dd/M/yy”并选择像 13/Aug/2011 这样的日期,它可以在 Chrome 中工作,但不会在 IE (v8.0.7600.16385) 中为我提交。在 FireFox (v3.6.18) 中,两种格式都可以使用。

What validation script do I need to be able to support date formats of 'dd/mm/yy' in Chrome?

我需要什么验证脚本才能在 Chrome 中支持“dd/mm/yy”的日期格式?

<html>
 <head>
  <link rel="stylesheet" type="text/css" href="jquery-ui.css" />
  <script type="text/javascript" src="jquery-1.4.4.js"></script>
  <script type="text/javascript" src="jquery.validate.js"></script>
  <script type="text/javascript" src="jquery.validate.unobtrusive.js"></script>
  <script type="text/javascript" src="jquery-ui.js"></script>
  <script type="text/javascript">
      $(document).ready(function () {
    $('.date').datepicker({ dateFormat: 'dd/mm/yy' });
            $.validator.addMethod("dateRule", function(value, element) {
      return true;
    },
    "Error message");
      });
  </script>
 </head>
 <body>
    <form>
        Date: <input type="text" name="myDate" class="date dateRule" />
        <input type="submit" />
    </form>
 </body>
</html>

采纳答案by sipwiz

Four hours later I finally stumbled across the answer. For some reason Chrome seems to have some inbuilt predilection to use US date formats where IE and FireFox are able to be sensible and use the regional settings on the OS.

四个小时后,我终于偶然发现了答案。出于某种原因,Chrome 似乎有一些内在的偏好,即使用美国日期格式,其中 IE 和 FireFox 能够明智地使用操作系统上的区域设置。

jQuery.validator.methods["date"] = function (value, element) { return true; } 

回答by magritte

You can use the Globalize.js plugin available here: https://github.com/jquery/globalize

您可以使用此处提供的 Globalize.js 插件:https: //github.com/jquery/globalize

Then simply redefine the validate method in your web site's main script file like so (avoid editing the jquery.validate.js library file as you may want to update it in future):

然后像这样简单地在您的网站的主脚本文件中重新定义验证方法(避免编辑 jquery.validate.js 库文件,因为您将来可能希望更新它):

$.validator.methods.date = function (value, element) {
    return this.optional(element) || Globalize.parseDate(value, "d/M/y", "en");
}

回答by webdevduck

I know I'm a bit late to the party, but here's the solution I used to Chrome validation not accepting UK format dates. A simple plug and play validation, it doesn't rely on any plugins or modifying any files. It will accept any date between 1/1/1900 and 31/31/2999, so US or UK format. Obviously there are invalid dates that will sneak past, but you can tweak the regex to your heart's content. This met my needs as it will be used on a low traffic area of the site, with server-side validation. The area of the site in question is built with ASP.net MVC.

我知道我参加聚会有点晚了,但这是我用于 Chrome 验证不接受英国格式日期的解决方案。一个简单的即插即用验证,它不依赖于任何插件或修改任何文件。它将接受 1/1/1900 和 31/31/2999 之间的任何日期,因此是美国或英国格式。显然,会有一些无效的日期会溜过去,但您可以根据自己的喜好调整正则表达式。这满足了我的需求,因为它将用于站点的低流量区域,并进行服务器端验证。有问题的站点区域是使用 ASP.net MVC 构建的。

jQuery.validator.methods.date = function(value, element) {
    var dateRegex = /^(0?[1-9]\/|[12]\d\/|3[01]\/){2}(19|20)\d\d$/;
    return this.optional(element) || dateRegex.test(value);
};

回答by mezoid

Looks like this issue has been raised with the JQuery team.

看起来这个问题已经向 JQuery 团队提出了。

https://github.com/jzaefferer/jquery-validation/issues/153

https://github.com/jzaefferer/jquery-validation/issues/153

Looks like the workaround for now is to use dateITA in additional-methods.js

看起来现在的解决方法是在additional-methods.js 中使用 dateITA

It looks like this:

它看起来像这样:

jQuery.validator.addMethod(
    "dateITA",
    function(value, element) {
        var check = false;
        var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
        if( re.test(value)){
            var adata = value.split('/');
            var gg = parseInt(adata[0],10);
            var mm = parseInt(adata[1],10);
            var aaaa = parseInt(adata[2],10);
            var xdata = new Date(aaaa,mm-1,gg);
            if ( ( xdata.getFullYear() == aaaa ) 
                   && ( xdata.getMonth () == mm - 1 ) 
                   && ( xdata.getDate() == gg ) )
                check = true;
            else
                check = false;
        } else
            check = false;
        return this.optional(element) || check;
    },
    "Please enter a correct date"
);

If you add that validator you can then attach your datepicker to the '.dateITA' class.

如果添加该验证器,则可以将日期选择器附加到“.dateITA”类。

Thus far this has worked well for me to get me beyond this stupid issue in Chrome.

到目前为止,这对我来说很有效,可以让我摆脱 Chrome 中的这个愚蠢问题。

回答by Brent

This remains a problem in .net mvc4, where the EditorForDateTimestill produces a data-val-dateattribute, despite clear documentation in the jQuery validation plugin not to use it!!! Hopefully microsoft fixes this and data-val-dateis never heard of again!

这仍然是 .net mvc4 中的一个问题,尽管 jQuery 验证插件中有明确的文档不使用它,但它EditorForDateTime仍然会生成一个data-val-date属性!!!希望微软解决这个问题,data-val-date再也没有听说过!

In the meantime you could use the suggested library via modernizr:

同时,您可以通过 Modernizr 使用建议的库:

yepnope({
    test: isNaN(Date.parse("23/2/2012")),
    nope: 'http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/additional-methods.min.js',
    complete: function () {
        $.validator.methods.date = $.validator.methods.dateITA
    }
});

or if not wanting to use yepnope/modernizr, and to get rid of the UTC component of the dateITA method (if using this library to enter a local time, dates will not always validate on the 1st or last day of the month unless on the Greenwich line - i.e. UTC +0):

或者如果不想使用 yepnope/modernizr,并摆脱 dateITA 方法的 UTC 组件(如果使用此库输入本地时间,则日期不会总是在当月的第一天或最后一天验证,除非在格林威治线 - 即 UTC +0):

(function ($) {
    var invokeTestDate = function () {
        return $.validator.methods.date.call({
            optional: function () {
                return false;
            }, (new Date(2012,8,23)).toLocaleDateString(), null);
    };
    if (invokeTestDate()) {
        return;
    }

    // http://docs.jquery.com/Plugins/Validation/Methods/date

    $.validator.methods.date = function (value, element) {
        //ES - Chrome does not use the locale when new Date objects instantiated:
        //return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        var d = new Date();
        return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
    }
})(jQuery);

回答by Tarquin

I found the simplest correction of this error to be the following code snippet after calling your validation file;

在调用您的验证文件后,我发现此错误的最简单更正是以下代码片段;

    jQuery.validator.methods["date"] = function (value, element){
        var shortDateFormat = "dd/mm/yy";
        var res = true;
        try {
            $.datepicker.parseDate(shortDateFormat, value);
        } catch (error) {
            res = false;
        }
        return res;
    }

Even in versions found in 2016 im still having this issue without the above code in Chrome and not Firefox.

即使在 2016 年发现的版本中,如果没有 Chrome 而不是 Firefox 中的上述代码,我仍然存在此问题。

This is my preferred solution as it does not require any additional libraries or plugins to work.

这是我的首选解决方案,因为它不需要任何额外的库或插件即可工作。

I found this code snippet while googling the issue here.

我在这里搜索问题时发现了这个代码片段

回答by DiskJunky

We use the following to work on our projects;

我们使用以下内容来处理我们的项目;

if ($.validator) {
    $.validator.addMethod("date",
        function (value, element, params) {
            if (this.optional(element)) {
                return true;
            }

            var ok = true;
            try {
                $.datepicker.parseDate("dd/mm/yy", value);
            }
            catch (err) {
                ok = false;
            }
            return ok;
        });
}

回答by user2715347

May this code help you.

愿此代码对您有所帮助。

$.validator.addMethod(
         "date",
         function(value, element) {
              var check = false;
              var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
              var reBR = /^\d{4}\-\d{1,2}\-\d{1,2}$/;
              if( re.test(value)){
                   var adata = value.split('/');
                   var gg = parseInt(adata[0],10);
                   var mm = parseInt(adata[1],10);
                   var aaaa = parseInt(adata[2],10);
                   var xdata = new Date(aaaa,mm-1,gg);
                   if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
                        check = true;
                   else
                        check = false;
              } else if( reBR.test(value)){
                   var adata = value.split('-');
                   var aaaa = parseInt(adata[0],10);
                   var mm = parseInt(adata[1],10);
                   var gg = parseInt(adata[2],10);
                   var xdata = new Date(aaaa,mm-1,gg);
                   if ( ( xdata.getFullYear() == aaaa ) && ( xdata.getMonth () == mm - 1 ) && ( xdata.getDate() == gg ) )
                        check = true;
                   else
                        check = false;
              } else
                   check = false;
                   console.log(check);
              return this.optional(element) || check;
         },
         "Por favor insira uma data válida"
    );

回答by Kevin Wong

Or we might try to overwrite the validator instead of ignoring it.

或者我们可能会尝试覆盖验证器而不是忽略它。

$.validator.addMethod("date", function (value, element) {
    var result = true;
    try {
        $.datepicker.parseDate('dd/mm/yy', value);
    }
    catch (err) {
        result = false;
    }
    return result;
});

回答by Jodda

This is the only solution that worked for me: http://www.codeproject.com/Tips/579279/Fixing-jQuery-non-US-Date-Validation-for-Chrome

这是唯一对我有用的解决方案:http: //www.codeproject.com/Tips/579279/Fixing-jQuery-non-US-Date-Validation-for-Chrome

 jQuery.extend(jQuery.validator.methods, {
        date: function (value, element) {
            var isChrome = window.chrome;
            // make correction for chrome
            if (isChrome) {
                var d = new Date();
                return this.optional(element) || 
                !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
            }
            // leave default behavior
            else {
                return this.optional(element) || 
                !/Invalid|NaN/.test(new Date(value));
            }
        }
    });