zaterdag 31 december 2011

Html5 form validation

Hmtl5 supports form validation using declarations. Unfortunately not all browsers support this feature.

This weekend I sat down for creating a cross browser solutions using the standard html5 validation attributes.

I had to created a markup control to display a validation message next to the offending input and write some code to support cross field validation.

Html5 offers nothing for validating that an end date is after an entered start date. That is why I introduced the data-rules attribute.

In html5 when you add meta data for an element or field input the recommended way is to use data-* attributes. Have a look at jQuery Mobile how they used the data-role attribute.

The data-rules attribute can be used for multiple data declarations the same way the style attribute can be used for multiple style declarations.

Suppose you have a startdate and an enddate field and you want to enforce that the enddate is after the startdate
You can do this with the following attribute on the enddate field: data-rules="after:startdate"

Html5 gives you many new form field input types like date and number. I don't like the way some browsers handle these types in the user interface.
That is why I keep using type="text" in combination with the pattern attribute to define a regular expression.

To compensate for not using dedicated input types, I use the data-domain attribute. For example: data-domain="date-nl" to indicate a date in the dutch date format. The data-domain is then used by the validation routine.

It works very nice with a limited amount of javascript code and I use the available standard html5 validation attributes like: pattern, max and min.

0 reacties: