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.
Challenge: Try clicking Submit without typing anything. Then try typing a short name.
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().
JavaScript
Preview
Step B: Checking the Data
Now that we stopped the form, we can look at what the user typed.
We need to:
- Give the input an
id so we can find it.
- Use
document.getElementById('...').value to get the text.
- Use an
if statement to check it.
JavaScript
Preview
3. Final Challenge: The Age Gate
Mission: create a
validateAge() function.
- Get the value from the age input.
- If age is less than 18, show an alert saying "You are too young!".
- If age is 18 or older, show an alert saying "Welcome!".
JavaScript
Preview