DOM
Form Validation
Validate user input before submitting a form.
1. Explanation
Listen to the form's submit event, call event.preventDefault() to stop the page reload, then read input values and check them. Show error messages by updating the DOM. For accessibility also use the built-in HTML attributes like required, minlength, type=email.
2. Example
Try it yourself
Console
Click Run to see output.
3. Expected output
output
(shows error or submits)4. Common mistakes
- ✗Forgetting e.preventDefault() — the form submits and page reloads
- ✗Trusting client-side validation only — always validate on the server too
- ✗Using regex from the internet without understanding it
5. Practice questions
- Validate that password length is at least 8
- Validate that password and confirm-password match
- Validate a phone number is 10 digits