Before writing a single line of JavaScript validation, know that HTML gives you 80% of it free โ and browsers show the error messages automatically.
The validation toolkit
<input type="email" required> <!-- must be an email -->
<input type="text" minlength="3" maxlength="20">
<input type="number" min="1" max="100">
<input type="text" pattern="[0-9]{6}" <!-- 6-digit pincode -->
title="Enter a 6-digit pincode">
<input type="url"> <input type="tel">Styling invalid fields
input:invalid { border-color: red; }
input:valid { border-color: green; }
input:user-invalid { } /* only after the user touched it โ modern */When you still need JS
- Comparing two fields (password confirmation)
- Checking against a server (username taken?)
- Custom error UI
Even then, keep the HTML attributes โ they work when JS fails and help screen readers. Full form reference: Forms lesson.