How to validate web forms using HTML 5

HTML 5 provides some new ways of validating user intput, which could save you a lot of time writing javascript code. This guide demonstrates how to do several standard validation checks using only HTML.

Presence check

A presence check is the simplest check to do. Adding the required attribute to a form element will stop the form from submitting until the element has been filled in.

<input type="text" required />
Format check

There are several ways to do a format check. HTML 5 provides some new input types that combined with the required attribute can be used to validate what the user inputs; the new input types are shown below.

<input type="email" required />
<input type="url" required />
<input type="date" required />
<input type="time" required />
<input type="datetime" required />
<input type="datetime-local" required />
<input type="month" required />
<input type="week" required />

But what if there isn't a type for what you want to validate? There's a new pattern attribute that lets you validate using regular expressions. For example the code below could be used to validate country codes (US, UK, AU, etc).

<input type="text" required pattern="[A-Za-z]{2,3}" />

There's a lot more info on using and creating regular expressions at Regular-Expressions.info

Range check

There are two ways to make sure the user is selecting a number in your chosen range.

<input type="number" min="1" max="100" required />
<input type="range" min="1" max="100" required />
Both the number and range support the "step" attribute which lets you decide how much the numbers increase or decrease by. For example the code below would only accept multiples of 2 between 0 and 10.
<input type="number" min="0" max="10" step="2" required />
Length check

Maxlength isn't a new addition in HTML 5 but it is the easiest way to do a length check. As the attribute suggests it limits them amount of characters that can be typed into a text field or textarea. The code below will stop the user from entering any more than 30 characters into a text field.

<input type="text" maxlength="30" />
Drawbacks

Whilst the new validation methods are helpful they aren't perfect. First of all, they're only client side, anyone can bypass them by editing elements on the DOM. If you use these you should also do server side validation.

Another issue is all the browsers have different error message implementations and there is no way to change the look or feel of them. Whilst it is helpful for the average use to see consistent error messages the style of them might not fit with your site.

There is also no standard way to define what the error message says. Although Mozilla has the attribute x-moz-errormessage but unfortunately it's only implemented on FireFox.

blog comments powered by Disqus
Most recent
Most popular
Subscribe