HTML ยท Module 08 ยท Lesson 42 of 54

Form Validation Rules

What is Form Validation?

Imagine filling out a driver's license application. If you leave your age blank or write your phone number using letters, the clerk will reject the form immediately and ask you to fix it.

In HTML, you can write validation checks directly on your inputs to enforce rules before sending data:

  • required: Forces the user to fill out the input before submitting.
  • pattern="regex": Specifies a regular expression pattern that the input value must match (e.g., [0-9]{3} forces exactly three numbers).
  • minlength and maxlength: Limits the number of characters.
  • Why does it matter?

    Validation prevents bad data from reaching your database. It also provides instant helper prompts to site visitors, showing them mistakes immediately without waiting for a slow page reload.

    How to write it

    Add validation attributes directly to your input elements:
    <input type="text" id="code" required pattern="[0-9]{3}">
    

    โŒ Input is required

    Common Mistakes

  • **Relying *only* on HTML validation for security**: Smart users can easily bypass browser HTML validations by inspecting the page and deleting the attributes. Always validate data a second time on your backend server!
  • Quick Reference

  • required โ€” Input field cannot be left blank.
  • pattern="[0-9]{3}" โ€” Value must match the pattern.
  • minlength="N" and maxlength="N" โ€” Character constraints.
  • Your Task
    Add a validation check to the input: make it `required` and specify a `pattern` to match exactly three numbers: `[0-9]{3}`.
    index.html
    Type code above to start the lesson.
    Live Preview