Lesson 9: HTML Forms & Validation
HTML Forms & Validation
Lesson 09 · Making sure user input follows the rules.
What is form validation?
In Lesson 05, you learned how to create forms using HTML. But what happens when someone enters incorrect information?
Imagine a sign-up form that asks for an email address. Someone enters "hello" instead of a real email address. Should the form accept it?
This is where form validation comes in. Form validation checks whether the information entered by a user follows certain rules.
The required attribute
Sometimes a form needs certain information before it can be submitted. The required attribute makes a field mandatory.
Without the required attribute, the user could leave the field empty and still attempt to submit the form.
Try submitting without typing anything!
Checking email addresses
HTML has an input type specifically designed for email addresses: type="email".
The browser checks whether the entered value follows a basic email format before allowing the form to submit.
minlength and maxlength
You can control how many characters a user is allowed to enter.
minlength sets the minimum number of characters.
maxlength sets the maximum number of characters.
You can also use both together:
min and max
The min and max attributes can set the lowest and highest allowed values for number inputs.
In this example, the value must be between 1 and 100.
Creating input patterns
The pattern attribute lets you define a specific format that the user's input must match.
It uses something called a regular expression, often shortened to regex.
This pattern means:
- A-Z allows uppercase letters.
- a-z allows lowercase letters.
- {3,10} requires between 3 and 10 letters.
Taking validation further
HTML provides built-in validation, but JavaScript lets you add custom checks and messages.
One useful method is checkValidity(). It checks whether a form or input satisfies its validation rules.
Here is what these methods do:
- checkValidity() returns true or false depending on whether the input is valid.
- reportValidity() asks the browser to display its validation message.
Your turn: Build a registration form!
Now it's time to combine everything you've learned. Create a registration form with these requirements:
- A username that is required and between 3 and 15 characters.
- An email field that checks for a valid email format.
- An age field that accepts numbers between 13 and 100.
- A password field that requires at least 8 characters.
- A submit button.
Use this starter template:
Test your knowledge!
Choose the correct answer for each question.