HTML5 Constraint Validation API

HTML5 introduces the ability for browsers to validate data in forms before submitting to the
server. This capability enables basic validation even when JavaScript is unavailable or fails to load.
The browser itself handles performing the validation based on rules in the code and then displays
appropriate error messages on its own (without needing additional JavaScript). Of course, this
functionality works only in browsers that support this part of HTML5, including Firefox 4+,
Safari 5+, Chrome, and Opera 10+.
Validation is applied to a form fi eld only under certain conditions. You can use HTML markup to
specify constraints on a particular fi eld that will result in the browser automatically performing
form validation.

Required Fields
The fi rst condition is when a form fi eld has a required attribute, as in this example:

<input type=”text” name=”username” required>

Any field marked as required must have a value in order for the form to be submitted. This
attribute applies to <input>, <textarea>, and <select> fi elds (Opera through version 11 doesn’t
support required on <select>). You can check to see if a form fi eld is required in JavaScript by
using the corresponding required property on the element:
var isUsernameRequired = document.forms[0].elements[“username”].required;
You can also test to see if the browser supports the required attribute using this code snippet:
var isRequiredSupported = “required” in document.createElement(“input”);
This code uses simple feature detection to determine if the property required exists on a newly
created <input> element.

Keep in mind that different browsers behave differently when a form fi eld is required. Firefox 4 and
Opera 11 prevent the form from submitting and pop up a help box beneath the fi eld, while Safari (as
of version 5) and Chrome (as of version 9) do nothing and don’t prevent the form from submitting.