How to build and validate an HTML form the right way
Forms are where users actually interact with your site: sign-ups, contact pages, checkouts. Getting the basics right makes them easier to use and harder to abuse.
Start with solid HTML
- Wrap fields in a
<form>with anactionandmethod. - Give every input a
<label>connected withforandid. Clicking the label focuses the field, and screen readers announce it. - Use the right input
type:email,tel,number,date,password. Phones show suitable keyboards. - Add
autocompleteattributes (name,email,street-address) so browsers and password managers can fill fields. - Use a real
<button type="submit">.
Built-in validation
HTML provides validation without JavaScript:
requiredminlengthandmaxlengthmin,maxandstepfor numberspatternfor simple formatstype="email"andtype="url"checks
Improve with JavaScript
Show helpful messages near the field, validate as users finish typing a field (not on every keystroke), and keep their input when there's an error.
Always validate on the server
Client-side checks are for convenience. Anyone can bypass them, so the server must validate and sanitize everything again.
Usability tips
- Ask only for what you need.
- Mark optional fields rather than filling the form with asterisks.
- Write error messages that explain how to fix the problem.
- Don't clear the form on errors.
- Protect against spam with rate limiting or other server-side measures.
What's the most frustrating form you've had to fill out? Do you rely on built-in validation or a library?
Comments · 3
Validate on both sides. Browser checks are for convenience, but the server must check everything, because anyone can bypass the client.
Use the right input types, like email and tel. On a phone they bring up the correct keyboard, which is a huge usability bonus.
Make error messages say what to fix. "Invalid input" helps nobody, but "Password needs at least 8 characters" does.