JavaScript – RegExp To Validate Any Date

If you want to validate virtually any date (formatted as YYYY/MM/DD or YYYY-MM-DD) in JavaScript with a regular expression, you can use the following (fixed on August 8, 2013):

/^(?!(?![02468][048]|[13579][26]00)..(?!(?!00)[02468][048]|[13579][26])...02.29)\d{4}([\/-])(?=0.|1[012])(?!(0[13578]|1[02]).31|02.3)\d\d\1[012]|3[01]$/

This was actually inspired by the regular expressions from this post. Of course, the best way to check a date’s validity in JavaScript is to simply use the Date() function. Here is an example function which will do either YYYY/MM/DD or MM/DD/YYYY:

function validateDate(strDate) {
  var t = /^(?=.+([\/.-])..\1)(?=.{10}$)(?:(\d{4}).|)(\d\d).(\d\d)(?:.(\d{4})|)$/;
  strDate.replace(t, function($, _, y, m, d, y2) {
    $ = new Date(y = y || y2, m, d);
    t = $.getFullYear() != y || $.getMonth() != m || $.getDate() != d;
  });
  return !t;
}

If you have used other code segments from me, you have probably realized that the above, hard-to-understand-at-a-first-glance code is normal for me. Basically, it simply reads in the year, month and day of the month into the Date() function and makes sure that the outputted date still has the same data that was sent in. Have fun! 8)

One Reply to “JavaScript – RegExp To Validate Any Date”

Leave a Reply

Your email address will not be published. Required fields are marked *