Zhu Wu's Blog

The world is a fine place and worth fighting for.

A Little Trick on Front End Validation for Date Format

Suppose we have a text input field for user to input date in certain format (e.g., DD/MM/YYYY). How can we do front end validation correctly on this field?

It is easy to come up an idea that the date string can be validated against regular expression. For example, we can write a regular expression like ^\d{2}\/\d{2}\/\d{4}$ and check whether the input matches the regular expression or not. In this way, we can make sure that we have two digits in DD portion, two digits in MM portion, four digits in YYYY portion, and two forward slashes exists in the correct positions. We can even improve the regular expression with more advanced logic, e.g., to make sure that the first digit of DD will not be larger than 3 or the second digit of MM will not be larger than 2 when the first digit of MM is 1, etc.

After regular expression validation is applied, we can ensure that the input is conformed to basic format. However, even the most advanced regular expression for date format cannot fully check the correctness of a date, because it is impossible to use regular expression to determine whether February has 28 or 29 days in the year entered by user. Here is the trick:

  1. Split the date string into day, month and year according to delimiter.
  2. Construct a JavaScript Date object by passing year, month, and day into constructor. If any value passed into constructor is not inside its logical range, JavaScript will automatically "correct" it by adjusting the value of its adjacent values. For example, new Date(2015, 1, 29) will be automatically corrected to new Date(2015, 2, 1).
  3. Get day, month and year value from the newly constructed JavaScript Date object and compare them with the values retrieved from step 1. If any of them mismatch, the input date has a wrong format.

In this way, we can use a very simple regular expression (just like ^\d{2}\/\d{2}\/\d{4}$, so you can stay away from the headache to write and maintain a complex regular expression) in the first step of validation, and fully ensure the correctness of date string input by user by applying the trick in step 2. Here is the sample code which returns true if the date string passed validation:

function checkDate(dateStr) {
  if (/^\d{2}\/\d{2}\/\d{4}$/.test(dateStr)) {
    var dayMonthYear = dateStr.split('/'),
        day = parseInt(dayMonthYear[0]),
        month = parseInt(dayMonthYear[1]),
        year = parseInt(dayMonthYear[2]),
        newDate = new Date(year, month - 1, day);
    return day === newDate.getDate() && month === newDate.getMonth() + 1 && year === newDate.getFullYear();

  return false;

Finally, please take note that Date class in JavaScript does not support Julian calendar. You need additional effort if you are dealing with historical dates in JavaScript. Find out more in my previous post for how to handle historical date in Java.