Inserting data into forms is one of the most trivial tasks for any application. Most of the data is simple like inputs, radio buttons, checkboxs or textareas.

There are, however, some field types that have been causing controversy about the best way to fill those fields. In this post we talk about date fields and how you can format the input in order to provide an easy-to-use application.

A lot has changed since the first datepicker was introduced. However, we keep working with applications that aren’t easy to use and the users struggle to fill date fields in the correct format.

There was a time when a date field was just one more input field. The user was responsible for entering the data with the correct format and just a few applications told the user what the correct format was. After this, we jumped to a mix of

  • An input field
  • Three selects, one for each part (day, month and year)
  • Using datepickers that enforce a date format and enable the user to type the date

After all these years and we keep discussing what is the best way to enter date values.

In my opinion, the most common difficulty is due to the required date format. It’s common to see applications that target a given market with a date format different from that market (for example, the Portuguese date format is dd-mm-yyyy and there are many applications that require date fields with the format yyyy-mm-dd). This is probably related to the fact that database’s types DATA and DATETIME store dates with yyyy-mm-aa (funny thing, the most common date format is dd-mm-yyyy).

This means that most applications show dates as they are retrieved from the database. Using the same logic, if the user enters the date with a format that doesn’t match the database’s, he will be presented with a beautiful error message. This happens despite the programming language used (.net, Java or PHP).

In order to create applications with user experience in mind, the programmer should provide ways for the user to enter date fields in multiple formats. This can be achieved with a few lines of Javascript code. This way, we allow our users to enter date fields in multiple formats and then parse that value in order to insert the date with the correct database format. The following code allows the user to enter dates in multiple formats (dd-mm-yyyy, dd/mm/yyyy, d/m/yyyy, ddmmyyyy)

First we need to create a small function that will parse the value entered by the user:

var parseDate = function(value) {
    var m = value.match(/^(\d{1,2})(\/|-)?(\d{1,2})(\/|-)?(\d{4})$/);
    if (m)
        value = m[5] + '-' + ("00" + m[3]).slice(-2) + '-' + ("00" + m[1]).slice(-2);

    return value;
}

So we check if the entered value matches our regex. The value will match our regex when it’s composed by one or two digits followed by one or none / or -, followed by one or two digits followed by one or none / or -, ending in four digits. If the value matches, the user entered a value with the correct format and we will update that value.

However, the correct format doesn’t mean a valid date. So we’ll also need to validate the value as a valida date and we can do that with Date.parse():

var isValidDate = function(value, format) {
    format = format || false;
    // lets parse the date
    if (format) {
        value = parseDate(value);
    }

    var timestamp = Date.parse(value);

    return isNaN(timestamp) == false;
}

In order to use this code we only need to bind the parseDate to the input using the blur event:

$('input[name=datepicker]').on("blur",function () {
    // check if the date is correct. We accept dd-mm-yyyy or yyyy-mm-dd.
    // update the format to yyyy-mm-dd
    var date = parseDate($(this).val());

    if (! isValidDate(date)) {
        // Date isn't valid. Set the current date instead
        date = moment().format('YYYY-MM-DD');
    }

    $(this).val(date);
});

The following live example has all the code and uses the Bootstrap Datepicker.

See the Pen Simple Bootstrap datepicker example by Luís Cruz (@milz) on CodePen.

Since version 4.0 of this datepicker, which was released a couple weeks ago, its also possible to set multiple date formats without any aditional javascript code.