How HTML5 validation works

The basic idea behind HTML5 validation is, that you tell the browser which fields you want validated but donít actually do the tedious implementation yourself. As you define what state your input field is in you also asks the browser to validate the field client-side based on the type of input field.

Unfortunately not all modern browsers understand this new way of validating forms but donít worry. If you are using a type value the browser doesnít recognize, it will just treat is as a regular text field and no harm has been done. That means that all the following input elements get treated exactly the same:

<form>
	<input type="text" /> <br />
	<input type="my-weird-value" /> <br />
	<input />  <br />
	<input type="submit" value="Submit now" />
</form>

And why is this useful information when we are talking about validation? Because some of the input types discussed will not be supported by all browsers but this should not hold you from implementing the new HTML5 validation tricks.

Example - the required attribute

Letís say you have a regular text input field that cannot be left blank Ė then you use the attribute required. HTML5 allows you to shorten you markup when using the required attribute, so instead of writing it the long way:

<form>
	<input type="text" required="required" /><br />
	<input type="submit" value="Submit now" />
</form>

You can just write:

<form>
	<input type="text" required /><br />
	<input type="submit" value="Submit now" />
</form>

Using this required attribute the browser informs the user that she has to fill out this particular field before submitting the form. The required attribute do not take into consideration what kinds of data are typed into the input fields but you do have the opportunity to do this with some of the following input types. Now let's go have a look at them in the following chapters!