Table of Content
A date and time field can be easily found in many web forms. Typical applications are like ticket booking, appointment booking, ordering pizza, etc.
As of writing, the only web browser completely supports date time input is Opera (v11) and Google Chrome (v20). In HTML5, it is the job of the web browser to ensure the user can only enter a valid date time string into the input textbox.
Picking a date from the calendar is not the only way to input a date value even though it’s the most popular implementation. HTML5 specifications do not mention anything about displaying a calendar for date input.
The controls vary in general from browser to browser; at the moment support is patchy. In unsupported browsers, the control degrades gracefully to a simple <input type=”text”>.
What are the additional date input attributes?
In addition to the attributes common to all <input> elements, “date” inputs offer the following attributes: max, min, readonly, and step.
How to use date inputs in HTML5?
Date inputs sound convenient at first glance — they provide an easy UI for choosing dates, and they normalize the data format sent to the server, regardless of the user’s locale. However, there are issues with <input type=”date”> because of the limited browser support.
We’ll look at primary and more sophisticated uses of <input type=”date”>, then offer advice on mitigating the browser support issue later on (see Handling browser support). Of course, hopefully over time, browser support will become more ubiquitous, and this problem will fade away.
How to validate a date input?
By default, <input type=”date”> does not apply any validation to entered values. The UI implementations generally don’t let you enter anything that isn’t a date — which is helpful — but you can still leave the field empty or (in browsers where the input falls back to type text) enter an invalid date (e.g., the 32nd of June).
If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is outside the set bounds. However, you’ll have to check the results to be sure the value is within these dates since they’re only enforced if the date picker is fully supported on the user’s device.
Also, you can use the required attribute to make filling in the date mandatory — again, an error will be displayed if you try to submit an empty date field. This, at least, should work in most browsers.
How to handle browser support?
As mentioned above, the major problem with using date inputs at the time of writing is browser support.
Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.
One way around this is to put a pattern attribute on your date input. Even though the date input doesn’t use it, the text input fallback will.