Section 21: Built-in Validation and Constraints
Learning Objectives
- Understand browser-based form validation.
- Use required, minlength, maxlength, min, max and step.
- Understand email, URL and pattern validation.
- Learn novalidate and the limitations of client-side validation.
1. What Is Form Validation?
Validation checks whether entered information meets specified rules before submission. HTML provides built-in constraints that browsers can evaluate without custom JavaScript.
2. The required Attribute
<form action="/register" method="post">
<label for="username">Username</label>
<input id="username" name="username" required>
<button type="submit">Register</button>
</form>If the required field is empty, the browser normally blocks submission and displays a validation message.
3. Text Length Constraints
<label for="username">Username</label>
<input
id="username"
name="username"
type="text"
minlength="3"
maxlength="20"
required>minlength and maxlength set limits on the length of entered text. They do not enforce application-specific rules such as preventing duplicate usernames.
4. Numeric and Date Constraints
<label for="age">Age</label>
<input id="age" name="age" type="number" min="18" max="100" required>
<label for="appointment">Appointment Date</label>
<input id="appointment" name="appointment" type="date"
min="2026-01-01" max="2027-12-31" required>For supported controls, min and max constrain the permitted range. The server should also validate dates and numeric values according to the application's actual business rules.
5. The step Attribute
<label for="quantity">Quantity</label>
<input id="quantity" name="quantity" type="number"
min="1" max="20" step="1" required>
<label for="price">Price</label>
<input id="price" name="price" type="number"
min="0" step="0.01" required>step specifies allowed increments for supported controls. The default step depends on the input type. Use an appropriate step for the data being collected.
6. Email and URL Validation
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<label for="website">Website</label>
<input id="website" name="website" type="url">These types provide basic browser validation, but they do not prove that an email inbox exists or that a website is reachable.
7. Pattern Validation
The pattern attribute defines a regular expression for supported text-like input types. The entered value must match the required pattern for validation to pass.
<label for="code">Product Code (3 uppercase letters)</label>
<input id="code" name="code" type="text"
pattern="[A-Z]{3}"
title="Enter exactly three uppercase letters"
required>The pattern is matched against the entire value. Do not use a pattern as a replacement for server-side validation. For phone numbers, avoid overly restrictive patterns because valid formats vary by country.