Imagine you want to use a `date` input field


     <input type="date" name="birthday">

Unfortunately, each browser handles this field differently. Lets take a look at some examples:

It is written in the HTML5 date input specification that the date format is given as yyyy-mm-dd. Even though the date in the input field from Firefox, iOS Safari and Chrome appear to be of the format dd.mm.yyyy the actual value that is submitted from this form will be given as yyyy-mm-dd. The problem with all browser which do not support a date-picker, for instance IE, is that the user can input the date in any format he wishes to. If the user submits 01.01.2019 things will stop working at the backend, where a date of the form yyyy-mm-dd is expected.

Solution A

A quick-fix to handle this is by using HTML5 Date Patterns to enforce a date format when no date-picker is given.


     <input type="date" name="birthday" placeholder='YYYY-MM-DD' pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" >

The date-picker in the other browsers would remain and the user gets a hint in the IE what kind of value he has to enter.

In addition, the browser gives a user-friendly hint if the entered date is not valid

Solution B

Another solution is to use the jQuery date-picker if the browser has no native date-picker. Simply detect with Modernizr if the browser has a native date-picker or not. To get this done you need to include the jQuery UI and Modernizr scripts and add the following snippet to your code (credits to TJ VanToll):



This will give you the following date-picker for browsers like IE:

Remarks

  • Some people tend to simply change the type to `text`:
    
         <input type="text" name="birthday">
    

    and just always use the jQuery date-picker. This is a bad choice, since the jQuery date-picker is pretty hard to use on a mobile device.

  • If you are using the jQuery validation plugin, its probably best to ignore the date field:
    
        ignore: "input[type='date']"
    

    There are some unresolved issues with date-picker and the plugin.

Leave a comment

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