🎓 A1Learner
🔍

HTML Form Validation

Form validation is the checking a browser does on form answers before sending them. The browser blocks the send and flags a field that fails a check.

A required field

Required marks a field that must not stay empty. An empty required field stops the send and gets flagged.

<form>
<label for="n">Name</label>
<input type="text" id="n" name="n" required>
<button type="submit">Send</button>
</form>

An email type check

An email field checks that the answer looks like an address. Text without an at sign fails the check.

<form>
<label for="e">Email</label>
<input type="email" id="e" name="e">
<button type="submit">Send</button>
</form>

A pattern check

A pattern sets a text pattern the answer must match. This pattern means exactly three digits.

<form>
<label for="c">Code with 3 digits</label>
<input type="text" id="c" name="c" pattern="[0-9]{3}">
<button type="submit">Send</button>
</form>

Min and max checks

Min sets the smallest allowed number. Max sets the largest allowed number.

<form>
<label for="g">Guests from 1 to 10</label>
<input type="number" id="g" name="g" min="1" max="10">
<button type="submit">Send</button>
</form>

Example

<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
</head>
<body>
<h1>Book a Seat</h1>
<p>All fields are checked before booking.</p>
<form>
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="seats">Seats</label>
<input type="number" id="seats" name="seats" min="1" max="4">
<button type="submit">Book now</button>
</form>
</body>
</html>

Key points

  • Validation: the checks a browser runs before a form is sent
  • Required: a setting that makes a field impossible to leave empty
  • Pattern: a text pattern that an answer must match
  • Min and max: the lowest and highest numbers a number field accepts
  • The browser checks answers first and sends only answers that pass.

In this example, the form carries three checked fields. The name field is required, so it cannot stay empty. The email field is required and checks the shape of the address. The seats field accepts numbers from one to four only. The browser runs all checks when the button is clicked, and it sends the form only if every answer passes.

Note

Validation helps honest visitors catch slips. A receiving program still checks answers again.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does the required attribute do?