Form Validation
required, pattern, type attributes
Skills taught: html.validation, html.required, html.pattern, html.constraint-validation
HTML5 validation attributes prevent form submission when inputs don't meet requirements — no JavaScript needed.
<label for="name">Full name</label>
<input type="text" id="name" name="name" required>
**type** attributes add format validation automatically:
<!-- Must be a valid email format -->
<input type="email" name="email" required>
<!-- Must be a valid URL -->
<input type="url" name="website" placeholder="https://">
<!-- Must be a number between 1 and 100 -->
<input type="number" name="age" min="1" max="100">
<!-- Date picker -->
<input type="date" name="birthday" min="1900-01-01">
**minlength** and **maxlength** set character limits:
<label for="username">Username (3–20 characters)</label>
<input type="text" id="username" name="username"
minlength="3" maxlength="20" required>
**pattern** accepts a JavaScript regular expression to validate custom formats:
<!-- Only letters and numbers, 3-16 chars -->
<input type="text" name="username"
pattern="[a-zA-Z0-9]{3,16}"
title="3 to 16 letters and numbers only"
required>
<!-- Indian phone number -->
<input type="tel" name="phone"
pattern="[6-9][0-9]{9}"
title="Enter a valid 10-digit Indian mobile number">
Tip:
<form>
<label for="email">Email</label>
<input type="email" id="email" name="email" required autocomplete="email">
<label for="pw">Password (min 8 characters)</label>
<input type="password" id="pw" name="password"
minlength="8" required autocomplete="new-password">
<label for="age">Age</label>
<input type="number" id="age" name="age" min="13" max="120" required>
<button type="submit">Sign up</button>
</form>
Use **:valid** and **:invalid** CSS pseudo-classes to style inputs based on their validation state:
<style>
input:valid { border-color: green; }
input:invalid { border-color: red; }
</style>
<input type="email" placeholder="you@example.com">
Warning:
Frequently Asked Questions
How do I show custom error messages?
Use setCustomValidity('Your message') in JavaScript on the invalid event. Call setCustomValidity('') to clear the error when the field is valid.
Can I disable native browser validation?
Yes. Add novalidate to the form element. This disables the native UI but keeps the constraint validation API available so JavaScript can still call checkValidity().
Why does :invalid trigger immediately on page load?
A required empty field is technically invalid as soon as the page loads. Use :invalid with a :not(:placeholder-shown) or :user-invalid (modern browsers) selector to only show errors after the user has interacted with the field.