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
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
This happens because 12/05/20
which is a substring of your input 12/05/20-0
is a valid date.
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.
So its better to use a library function do this validation.
I was able to find one such library: 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)
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. 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).
This will still take some bad dates (such as 02/30/2000), but for practical purposes it should be good enough. This will also put month, day and year in capture groups 1, 2, and 3 respectively.
精彩评论