Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 = /d{1,2}[/-]d{1,2}[/-]d{4}/;
var reShort = /d{1,2}[/-]d{1,2}[/-]d{2}/;
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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...