All tutorials
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

  1. Validate that password length is at least 8
  2. Validate that password and confirm-password match
  3. Validate a phone number is 10 digits
→ Try more practice problems