A few months ago Sandeep introduced us to the HTML Constraint API, showing how we can use the new HTML5 input types and attributes to validate our forms in the browser with minimal Java Script.Today I’m going to walk you through validating a simple booking form by using the Constraint API, and keep an eye on how you can make sure your forms stay accessible too.I’m also using the WAI ARIA attribute now, so if we leave ‘required’ in the label tag screen reader users will have ‘required’ read to them twice, which they could find rather annoying.
To make sure our user enters the right data in the email, website, and number of tickets fields, we can use some of the new input types added in HTML5: By specifying the appropriate type, our browser will validate the data for us and make sure we've got an email address in the email field, a URL in the website field, and a number in the number of tickets field.
Note too that the If the user enters anything less than 1 or greater than 4, they'll be prompted to enter a number in the permitted range.
We can achieve this by adding a pattern attribute to the 'Name' field, setting it's value to the regular expression we want the data to be compared against: The text in the title attribute is then appended to the built-in validation message: Note that some screen reader / browser combinations might lead to the title attribute being read out in addition to the aria-describedby text, so watch out for this e.g.
I found that using NVDA with IE10 caused the title attribute and the aria-describedby element's text to be read out, but using NVDA with Chrome and Firefox didn’t exhibit this behaviour. Later on we’ll revisit this and show you one solution using CSS3.
Strictly speaking, you should make sure you're using the HTML5 DOCTYPE, otherwise you'll run into HTML validation errors.
But the great thing about them is that they all degrade gracefully.It also means that if you click the label, the associated input tag receives the focus.They also help with accessibility, as the text in the label will be read out to screen reader users: it can therefore be useful to indicate required fields by adding ‘required’ to the label text, as I’ve done above.To recap—or in case you haven’t read Sandeep’s article—with the dawn of HTML5, a raft of new input types and attributes were added to tags that allow the browsers themselves to perform the client-side validation for us: no Java Script required.To start using the new input types and attributes, you don't really need to do anything other than start using the new input types and attributes.Libraries such as Modernizr can help with HTML5 feature detection, but you can always write your own code if you don't want to include another Java Script library: In this article we've walked through applying HTML5 form validation to a booking form client-side without using any Java Script, and pointed out some accessibility issues to be wary of.