HTML

Form Validation

Form validation ensures that users enter correct and required information before submitting a form.

HTML provides built-in validation attributes that allow browsers to validate form data without JavaScript.

Common validation attributes include:

  • required
  • minlength
  • maxlength
  • min
  • max
  • pattern
  • type
<form>

    <label for="name">
        Full Name:
    </label>

    <input
        type="text"
        id="name"
        name="name"
        required
        minlength="3"
        maxlength="50"
    >

    <br><br>

    <label for="email">
        Email:
    </label>

    <input
        type="email"
        id="email"
        name="email"
        required
    >

    <br><br>

    <label for="age">
        Age:
    </label>

    <input
        type="number"
        id="age"
        name="age"
        min="18"
        max="60"
    >

    <br><br>

    <button type="submit">
        Submit
    </button>

</form>

required

The required attribute makes a field mandatory.

<input
    type="text"
    required >

The form cannot be submitted if the field is empty.

minlength

Specifies the minimum number of characters.

<input
    type="text"
    minlength="3" >

The user must enter at least 3 characters.

maxlength

Specifies the maximum number of characters.

<input
    type="text"
    maxlength="20" >

The user cannot enter more than 20 characters.

min and max

These attributes define the minimum and maximum allowed values.

<input
    type="number"
    min="18"
    max="60" >

The accepted value must be between 18 and 60.

type

The type attribute also provides validation.

<input type="email">

The browser checks whether the user enters a valid email address.

Other examples:

<input type="url">

<input type="number">

<input type="date">

pattern

The pattern attribute specifies a regular expression that the input must match.

Example: exactly 10 digits for a phone number:

<input
    type="tel"
    pattern="[0-9]{10}"
    placeholder="Enter 10-digit phone number" >
Interactive Sandbox
HTML/CSS/JS