TOC

The community is working on translating this tutorial into Arabic, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Form validation using HTML5:

Validating dates

HTML5 gives you different opportunities to validate dates. The browsers that understand the date element provide your users with handy drop down calendars to pick the dates from. This prevents your users from misunderstanding the date format or deliberately to pick incorrect or non-existing dates.

The date element provides you with six different ways f defining dates: date, month, week, time, date + time, and date + time – time zone. As of right now, the support is at best sparse as Opera is the only browser that provides these drop down calendars and Chrome provides the bare minimum – spinboxes in which the user cannot choose an invalid number. Therefore, if you want to implement the date element you would also have to use a polyfill to support it properly.

If you use the “Try this example" feature then please note that I have not implemented any polyfill to support the date element and therefore the example will reflect how your current browser actually renders the element.

Date

The format for the date type is YYYY-MM-DD, which means that May 14th 2012 would be rendered 2012-05-12. This is a classic choice for anything from vacation dates to delivery dates.

<form>
  <input type="date">
  <input type="submit" value="Submit Now!">
</form>

Month

The format for the month type is YYYY-MM, which means that May 2012 would be rendered 2012-05.

<form>
  <input type="month">
  <input type="submit" value="Submit Now!">
</form>

Week

Sometimes all you need is a week, and the format for the week type is YYYY-Www, which means that week 12 in 2012 would be rendered 2012-W12.

<form>
  <input type="week">
  <input type="submit" value="Submit Now!">
</form>

Time

Sometimes you need a specific time and the time type is renderes HH:mm:ss.ss but the seconds are optional. This means that 4.30 p.m. would be rendered 16:30 or if you choose to include seconds, 16:30:23.4

<form>
  <input type="time">
  <input type="submit" value="Submit Now!">
</form>

Date & Time

The datetime type has a long format: YYYY-MM-DD THH:mm:ss.s and May 14th 2012 would be rendered 2012-05-12 T16:30:23.4

<form>
  <input type="datetime">
  <input type="submit" value="Submit Now!">
</form>

What you have learned

  • There is several different ways of validating dates
  • The date attribute support is of right now very sparse and therefore you should consider using a polyfill to support it

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!
adplus-dvertising