Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

regex - 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 = /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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...