Form Validation Basics
Catch bad input before it's ever submitted, using nothing but built-in HTML attributes.
2 min de lectura
Browsers can validate form input on their own, before any JavaScript runs — it's often the fastest and most accessible way to catch obvious mistakes.
Required fields
<label for="email">Email</label>
<input type="email" id="email" name="email" required />required stops the form from submitting until the field has a value. Try submitting a form with an empty required field — the browser focuses it and shows a built-in tooltip, with no JavaScript involved.
Type-based validation
Some input types validate their own format automatically:
<input type="email" required />
<input type="url" required />type="email" rejects a submission if the value doesn't look like name@domain.tld. type="url" requires something that parses as a valid URL.
Length and range constraints
<input type="text" minlength="3" maxlength="20" />
<input type="number" min="1" max="100" />minlength/maxlength constrain text length; min/max constrain numeric (and date) ranges.
Pattern matching
For anything more specific, pattern accepts a regular expression:
<label for="zip">ZIP code</label>
<input type="text" id="zip" name="zip" pattern="[0-9]{5}" title="Enter a 5-digit ZIP code" />The title attribute doubles as the message shown when the pattern doesn't match, so always include one — otherwise the user just sees a generic "please match the requested format" with no idea what format is expected.
Styling validation states with CSS
Browsers expose :valid and :invalid pseudo-classes you can style:
input:invalid {
border-color: red;
}
input:valid {
border-color: green;
}HTML validation isn't enough on its own
Built-in validation is a great first line of defense for user experience — it gives instant feedback without a network round-trip. But it can be bypassed entirely (disabling JavaScript doesn't disable it, but a request crafted outside the browser skips it completely), so never trust it as your only line of defense. Always validate again on the server before doing anything with submitted data.