I recently embarked on improving the client-side form validation for a client. There were about 400 lines of form validation code stuffed inside a 1000 line
form_helper.js. I looked for lightweight form validation scripts but after some hemming and hawing I decided to try my hand (again) at native HTML5 Form Validation.
If you’ve ever experimented with HTML5 Form Validation, you’ve probably been disappointed. The out-of-box experience isn’t quite what you want. Adding the
requiredattribute to inputs works wonderfully. However the styling portion with
input:invalidsorta sucks because empty inputs are trigger the
:invalidstate, even before the user has interacted with the page.
I finally sat down and spent a couple days trying to make HTML5 Form Validation work the way I want it. I had the following goals:
- Leverage browser-level feedback, free focus management and accessible labelling
- Only validate inputs on submit
- Styling with
With this wishlist in hand, I set off and found a solution that works with only 6 lines of code.
If you ever wanted a mini-cheat sheet for what every part of a CSS rule is called, here it is:
- The whole thing is a ruleset.
- The curly braces and everything inside is a declaration block.
- The bit before the opening curly brace is a selector.
- Each key/value pair, as separated by a colon and ending in a semicolon, is a declaration.
- In those key/value pairs, the key is a property (or property name), and the value is a value (or property value).
This looks like a great resource for anyone wanting to get into web development and design.
This is a pretty neat interactive web development/design demo that shows how the different layers are applied, step by step, to create a web page.