TOC

This article is currently in the process of being translated into Spanish (~38% done).

Form validation using HTML5:

Validating dates

HTML5 ofrece diferentes oportunidades para validar fechas. Los exploradores que entienden el elemento de fecha proporcionan a los usuarios calendarios desplegables prácticos para elegir las fechas. Esto evita que los usuarios malinterpreten el formato de fecha o que seleccionen deliberadamente fechas incorrectas o no existentes.

El elemento date te proporciona seis formas diferentes de definir fechas: fecha, mes, semana, hora, fecha + hora y fecha + hora con zona horaria. Pero, el soporte es en el mejor de los casos escaso ya que Opera es el único navegador que proporciona estos calendarios desplegables y Chrome proporciona el mínimo - spinboxes en los que el usuario no puede elegir un número no válido. Por lo tanto, si deseas implementar el elemento de fecha, también tendría que utilizar un polyfill para admitirlo correctamente.

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!