Form Validation

Trust, but Verify.

Validation is the process of checking if the data a user entered is correct before we accept it. It prevents errors and security issues.

Validation Shield

1. The Easy Way: HTML5 Attributes

Modern browsers can do a lot of checking for you without writing any code! Just add special attributes to your inputs.

  • required: The field cannot be empty.
  • minlength="5": Must be at least 5 characters.
  • max="100": Number cannot be higher than 100.
HTML5 Validation Demo
Challenge: Try clicking Submit without typing anything. Then try typing a short name.
HTML
Preview

2. The Powerful Way: JavaScript

Sometimes we need more complex rules (like checking if two passwords match). For this, we use JavaScript to intercept the form submission.

Step A: Stop the Train!

By default, a form refreshes the page when submitted. We want to stop that so we can check the data first. We use event.preventDefault().

Stopping Form Submission
HTML
JavaScript
Preview

Step B: Checking the Data

Now that we stopped the form, we can look at what the user typed. We need to:

  1. Give the input an id so we can find it.
  2. Use document.getElementById('...').value to get the text.
  3. Use an if statement to check it.
Full Validation Example
HTML
JavaScript
Preview

3. Final Challenge: The Age Gate

Mission: create a validateAge() function.
  1. Get the value from the age input.
  2. If age is less than 18, show an alert saying "You are too young!".
  3. If age is 18 or older, show an alert saying "Welcome!".
Age Validation Challenge
HTML
JavaScript
Preview