Introduction to HTML5 form validation
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
required
attribute to inputs works wonderfully. However the styling portion withinput:invalid
sorta sucks because empty inputs are trigger the:invalid
state, 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
.error
classWith this wishlist in hand, I set off and found a solution that works with only 6 lines of code.