Chrome 中的低调验证不会使用 dd/mm/yyyy 进行验证

发布于 2024-11-27 07:43:45 字数 1325 浏览 3 评论 0原文

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

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

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

我需要什么验证脚本才能支持 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>

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

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.

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

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

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

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

发布评论

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

评论(12

幽梦紫曦~ 2024-12-04 07:43:46

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

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

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.

jQuery.validator.methods["date"] = function (value, element) { return true; } 
心的位置 2024-12-04 07:43:46

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

然后只需重新定义验证方法在您网站的主脚本文件中,如下所示(避免编辑 jquery.validate.js 库文件,因为您将来可能需要更新它):

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

You can use the Globalize.js plugin available here: 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):

$.validator.methods.date = function (value, element) {
    return this.optional(element) || Globalize.parseDate(value, "d/M/y", "en");
}
盗梦空间 2024-12-04 07:43:46

我知道我来晚了一点,但这是我用于 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);
};

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.

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);
};
长梦不多时 2024-12-04 07:43:46

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

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

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

它看起来像这样:

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

如果您添加然后,您可以将该验证器附加到“.dateITA”类中。

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

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

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

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

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.

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

云之铃。 2024-12-04 07:43:46

这在 .net mvc4 中仍然是一个问题,其中 EditorFor DateTime 仍然生成 data-val-date 属性,尽管 jQuery 中有明确的文档验证插件不要使用它!希望微软能够解决这个问题,并且再也不会听说 data-val-date 了!

同时,您可以通过 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
    }
});

或者如果不想使用 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);

This remains a problem in .net mvc4, where the EditorFor DateTime still produces a data-val-date attribute, despite clear documentation in the jQuery validation plugin not to use it!!! Hopefully microsoft fixes this and data-val-date is never heard of again!

In the meantime you could use the suggested library via 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):

(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);
惜醉颜 2024-12-04 07:43:46

我发现调用验证文件后最简单的错误纠正方法是以下代码片段;

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

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

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

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

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.

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.

北陌 2024-12-04 07:43:46

我们使用以下内容来开展我们的项目;

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

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;
        });
}
﹏雨一样淡蓝的深情 2024-12-04 07:43:46

希望这段代码对您有帮助。

$.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"
    );

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"
    );
自在安然 2024-12-04 07:43:46

应该将您在 validate 中定义的 dateRule 方法更改为(例如,正则表达式只是一个简单的方法):

$.validator.addMethod(
    "dateRule",
    function(value, element) {
        return value.match(/^\d\d?\/\d\d?\/\d\d$/);
    },
    "Please enter a date in the format dd/mm/yy"
);

您可以将正则表达式切换为您想要的任何内容。我从 此处 获取了此正则表达式,支持 M/D/YY 或 M/D /YYYY 或 MM/DD/YYYY 或 MM/DD/YY:1/1/1920 至 12/31/2019; 2 月 29 日和 30 日始终允许

^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$

should change the dateRule method you define in validate to (the regex is just a simple one for example):

$.validator.addMethod(
    "dateRule",
    function(value, element) {
        return value.match(/^\d\d?\/\d\d?\/\d\d$/);
    },
    "Please enter a date in the format dd/mm/yy"
);

you can switch the regex for whatever you wish. I got this regex for date from here which supports M/D/YY or M/D/YYYY or MM/DD/YYYY or MM/DD/YY: 1/1/1920 through 12/31/2019; Feb 29 and 30 always allowed

^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$
强辩 2024-12-04 07:43:46

这是唯一对我有用的解决方案:
http://www.codeproject.com /Tips/579279/修复 Chrome 的 jQuery-非美国日期验证

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

This is the only solution that worked for me:
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));
            }
        }
    }); 
拥有 2024-12-04 07:43:46

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

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

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;
});
一抹淡然 2024-12-04 07:43:46

我还找到了一个似乎适用于任何文化的解决方案。

http://devdens.blogspot.com/2011 /11/jquery-validation-fix-for-date-format_29.html

它需要你修改实际的 jquery.valdiation.min.js 文件,但到目前为止它对我有用。

I also found a solution that appears to work for any culture.

http://devdens.blogspot.com/2011/11/jquery-validation-fix-for-date-format_29.html

It requires you to modify the actual jquery.valdiation.min.js file, but so far it's working for me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文