date validation regular expression (improved formula catering for leap years and correct days in month)
Posted by Stefan Camilleri on {2008.August.6}
/** A friend of mine, João, very kindly pointed out a flaw in my date regex posted previously; the inability to validate the correct number of days in a month (30 or 31) */
Well, consider it done, this regex will now correctly validate days in a month as it should be (next I’ll try to cater for leap years) {
Date format is dd/mm/yy or dd/mm/yyyy (if you need US support let me know). Also note, that this regex does not use any lookbehind, so it should also work perfectly in JavaScript (which is probably where regex is used most anyway)
^(?:(?:0?[1-9])|(?:[12]\d)|(?:3(?:(?:0)|(?:1(?|(?:11))))))(?!(?:[\\.-/]\d{1,2}[\\.-/])(?:(?:[02468][048]00)|(?:(?:\d{2})?(?:(?:[2468][048])|(?:[13579][26])|(?:0[48]))))))[\\.-/](?:(?:0?[1-9])|(?:1[0-2]))[\\.-/](?:(?:\d{2})|(?:1\d{3})|(?:\d1\d{2})|(?:\d{2}1\d)|(?:\d{3}1))$
}
p.s. inevitably there will be bugs… so if you find any, let me know!
date validation regular expression « SZC’s Agglomeration said
[...] date validation regular expression (improved formula catering for leap years and correct days in&nbs… [...]
AlexM said
Your blog is interesting!
Keep up the good work!
Stefan Camilleri said
@AlexM
Thank you Alex
Suki said
Leap Year dates don’t seem to work. eg. 29/02/2000 comes back as invalid
Stefan Camilleri said
@Suki
Most leap years should work, that must’ve slipped.
Thank you for that… I’ll check it out
James said
this is excellent. Thanks for sharing.
Stefan Camilleri said
@James
You’re welcome
sunwatersnow said
Can you simply the code and show just how to validate the date part and not the time, and then throughly explain what is goin on.
And when you do could you email me the solution or posting at
steve_44@inbox.com
sunwatersnow said
I TESTED YOU YOUR STRING IN 5 REXEX APPLICATION
THE BUG IN YOU STRING IS
IT DOES NOT WORK
rc said
Some of the tests I’ve done:
02/31/2008 is NOT valid
11/3/2009 is NOT valid
4/23/1976 is NOT valid
8/32/1974 is NOT valid
1/1/1997 is valid
10/31/2018 is NOT valid
The lines in bold indicate your regex is not correct as those two dates are valid ones.