简体   繁体   English

使用正则表达式来验证javascript中mm / dd / yyyy格式的短日期和长日期

[英]Regular Expression to validate short and long date in mm/dd/yyyy format in javascript

I wanna validate date which can be either in short date format or long date format. 我想验证日期,可以是短日期格式也可以是长日期格式。 eg: for some of the valid date. 例如:对于某些有效日期。

12/05/2010 , 12/05/10 , 12-05-10, 12-05-2010 12/05/2010,12/05/10,12-05-10,12-05-2010

var reLong = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
var reShort = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{2}\b/;
var valid = (reLong.test(entry)) || (reShort.test(entry));
if(valid)
{
return true;
}
else
{
return false;
}

but this current regular expression fails when i try to give an invalid date as 12/05/20-0 但是当我尝试将无效日期设为12/05 / 20-0时,此当前正则表达式失败

This happens because 12/05/20 which is a substring of your input 12/05/20-0 is a valid date. 发生这种情况是因为12/05/20这是您输入的12/05/20 12/05/20-0的子字符串)是有效日期。

To avoid substring matches you can use anchors as: 为了避免子字符串匹配,可以将锚用作:

/^\d{1,2}[\/-]\d{1,2}[\/-]\d{4}$/

But again the above allows dates such as 00/00/0000 and 29/02/NON_LEAP_YEAR which are invalid. 但是以上内容再次允许使用无效的日期,例如00/00/000029/02/NON_LEAP_YEAR

So its better to use a library function do this validation. 因此最好使用库函数进行此验证。

I was able to find one such library: datajs 我能够找到一个这样的库: datajs

Here is a slightly more robust regex that will attempt to filter out some bad dates: 这是一个稍微更健壮的正则表达式,它将尝试过滤掉一些错误的日期:

^(1[012]|0[1-9])([\/\-])(0[1-9]|[12]\d|3[01])\2((?:19|20)?\d{2})$

Input (as seen on rubular ) 输入(如在ruular所示

01/01/2001  # valid
10-10-10    # valid
09/09/1998  # valid
00-00-0000  # invalid
15-15-2000  # invalid

Day matches: 01 to 31, month matches: 01-12 and year matches 1900-2099. 日比赛:01到31,月比赛:01-12和年比赛1900-2099。 It will also force you to enter a consistent separator (ie: mm/dd/yyyy and mm-dd-yyyy work, but mm-dd/yyyy doesn't). 它还会迫使您输入一个一致的分​​隔符(即: mm/dd/yyyymm-dd-yyyy ,但是mm-dd/yyyy无效)。

This will still take some bad dates (such as 02/30/2000), but for practical purposes it should be good enough. 这仍然会花费一些不好的日期(例如02/30/2000),但出于实际目的,它应该足够好。 This will also put month, day and year in capture groups 1, 2, and 3 respectively. 这还将把月份,日期和年份分别放在捕获组1、2和3中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM