HTML for Web Development

0% completed

Previous
Next
Form Validation

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.

What Is Form Validation?

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.

Common Validation Attributes

Here are some of the most used validation attributes:

  • required: Forces the user to fill in a field before submission.

    • Syntax Example:
    <input type="text" name="username" required>
  • pattern: Uses a regular expression to define a custom format that the input must match.

    • Syntax Example:
    <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.

    • Syntax Example:
    <input type="number" name="age" min="18" max="100">
  • step: Defines the interval between legal numbers in a range or number input.

    • Syntax Example:
    <input type="number" name="quantity" min="1" max="10" step="1">

Benefits of Built-In Validation

  • Better User Experience: The browser can alert users immediately when something is missing or entered in the wrong format.
  • Reduced Server Load: Basic checks are done by the browser before sending data to the server.
  • Improved Data Quality: With validation in place, you are more likely to receive correct and useful data.

Example: A Registration Form with Validation

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.

HTML

. . . .

Explanation

  • Username: The required attribute ensures that this field is not left empty.
  • Email: Using type="email" provides basic email format checking.
  • Password: The minlength and maxlength attributes enforce that the password length is between 8 and 16 characters.
  • Age: The min and max attributes make sure the age entered is between 18 and 100.
  • Zip Code: The pattern attribute uses a regular expression to require exactly 5 digits.
  • Submit Button: Clicking the submit button will prompt the browser to check all the specified validations. If any field does not meet its requirements, the form will not be submitted until the errors are corrected.

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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next