Native HTML Validation
Modern browsers can validate form input automatically, before any JavaScript runs, using built-in attributes. This is called constraint validation.
Validation Attributes
| Attribute | Effect |
|---|---|
| required | Field must be filled before the form can submit |
| minlength / maxlength | Restricts the number of characters |
| min / max | Restricts numeric or date range |
| pattern | Requires the value to match a regular expression |
| step | Restricts numeric input to multiples of a value |
Required and Length Validation
<input type="text" name="username" required minlength="3" maxlength="20" />Pattern Validation
<input
type="text"
name="zip"
pattern="[0-9]{5}"
title="Enter a 5-digit ZIP code"
required
/>Numeric Ranges
The min, max, and step attributes work with number, range, and date inputs to constrain acceptable values.
Numeric Range Validation
<input type="number" name="age" min="18" max="99" step="1" required />Built-in Type Validation
Types like email and url validate their format automatically. An input of type="email" will reject a value without an @ symbol, with no extra attributes needed.
Email Validation
<input type="email" name="email" required />Custom Error Messages
The title attribute is shown as part of the validation message when a pattern doesn’t match, giving users a hint about the expected format.
HTML Validation is Not Enough Alone
Native HTML validation improves user experience but can be bypassed (e.g. by disabling JavaScript-free form submission via dev tools). Always validate data again on the server.
Best Practice
Use HTML validation attributes as the first line of defense for a fast, accessible experience, and always re-validate submitted data on the server before trusting it.