0% completed
In this lesson, you'll learn how to use HTML's built-in validation features to help ensure that users enter the right data before the form is submitted. Using these techniques not only improves the user experience but also helps reduce errors when processing form data.
Form validation checks the user's input for correctness before the form data is sent to the server. HTML5 provides several attributes that let you specify rules directly in your form controls, so the browser can help users fix mistakes.
Here are some of the most used validation attributes:
required
: Forces the user to fill in a field before submission.
<input type="text" name="username" required>
pattern
: Uses a regular expression to define a custom format that the input must match.
<input type="text" name="zipcode" pattern="[0-9]{5}">
(This pattern requires exactly 5 digits.)
min
and max
: Specify minimum and maximum values for numeric inputs.
<input type="number" name="age" min="18" max="100">
step
: Defines the interval between legal numbers in a range or number input.
<input type="number" name="quantity" min="1" max="10" step="1">
Below is a complete HTML example that uses various validation attributes. This form collects a user's name, email, password, age, and zip code, and ensures the correct data is entered before submission.
required
attribute ensures that this field is not left empty.type="email"
provides basic email format checking.minlength
and maxlength
attributes enforce that the password length is between 8 and 16 characters.min
and max
attributes make sure the age entered is between 18 and 100.pattern
attribute uses a regular expression to require exactly 5 digits.Using these built-in validation features in your forms can significantly improve the overall experience for your users and help maintain data quality in your applications.
.....
.....
.....