SZC’s Agglomeration

{an agglomeration of laconic notes in relation to anything that sparks my interest}

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(?![\\.-/](?:(?:0?[2469])|(?: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!

10 Responses to “date validation regular expression (improved formula catering for leap years and correct days in month)”

  1. [...] date validation regular expression (improved formula catering for leap years and correct days in&nbs… [...]

  2. AlexM said

    Your blog is interesting!

    Keep up the good work!

  3. @AlexM

    Thank you Alex :)

  4. Suki said

    Leap Year dates don’t seem to work. eg. 29/02/2000 comes back as invalid

  5. @Suki
    Thank you for that… I’ll check it out :) Most leap years should work, that must’ve slipped.

  6. James said

    this is excellent. Thanks for sharing.

  7. @James

    You’re welcome :)

  8. 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

  9. sunwatersnow said

    I TESTED YOU YOUR STRING IN 5 REXEX APPLICATION
    THE BUG IN YOU STRING IS
    IT DOES NOT WORK

  10. 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.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>