Amazon.com Widgets

Agile Otaku

New Form Validation Feature of HTML 5

This is a continuation of my journey of learning HTML 5 from the book The Essential Guide to HTML5: Using Games to learn HTML5 and JavaScript

I like the book so far, it is certainly fun to learn through games.

In this post, I want to talk about the new HTML 5 form validation feature.

When writing an html form as below,

<form>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
Age : <input type="text" name="age" />
Email : <input type="text" name="email" />
Website: <input type="text" name="website" />
</form>

and we need to validate, we usually need to pass it to the server-side, perform validation there then re-render the page with the validation error marker. Oh well, I can still remember how long it takes to refresh the page just to show the validation error. With the advent of AJAX and better knowledge of javascript, we no longer have to submit the form, we can immediately do the validation while the user is typing through javascript. JQuery is very useful in this scenario.

But with html 5, you no longer have to do that.

Now we can specify the field's type and validate it in place without much coding effort. It supports numbers, email and URLs.

<form>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
Age : <input type="number" name="age" />
Email : <input type="email" name="email" />
Website: <input type="url" name="website" />
</form>

Compared to the previous example, we can specify the type of the field. We can then use css to change the color if the field is valid or invalid.

input:valid {background:white;}
input:invalid {background:red;}

This will result to the following

Notice, I did not write a single javascript!

See the live demo here

Comments