HTML5 Form Validation & Constraint Validation API
Master native declarative validation attributes, JavaScript Constraint Validation API (validity object), modern CSS validation pseudo-classes (:user-valid), and security rules.
1. Declarative HTML5 Validation Attributes
Prior to HTML5, developers were forced to write dozens of lines of tedious JavaScript regex handlers just to check if an email had an @ symbol. Modern HTML5 provides native declarative validation attributes executed directly by the browser's C++ rendering engine before any JavaScript runs:
💡 Real-World Analogy: Airport Security Passport Gate
Think of form validation like airport security checkpoints:
• required is verifying you have a passport in your hand before stepping in line.
• pattern="[A-Z]{5}[0-9]{4}[A-Z]{1}" is the biometric scanner verifying the exact character pattern format (like a PAN card).
• min & max are baggage weight scales rejecting parcels outside accepted thresholds.
Presence & Length
Character Thresholds
required: Blocks submission if field is empty or unselected.minlength="8": Minimum character count.maxlength="30": Prevents typing beyond limit.
Numeric & Date Bounds
Quantity Boundaries
min="18"/max="60": Numeric / Date lower and upper limits.step="0.5": Allowed numerical increments (e.g. half-step GPA scores).
Pattern Matching (Regex)
Strict Format Matching
pattern="[0-9]{10}": 10-digit mobile number.title="...": Custom hint shown in native tooltip when pattern fails.
<form action="/apply" method="POST">
<!-- 1. Character Length Range (3-15 chars) -->
<label for="username">Username (3-15 chars):</label>
<input type="text" id="username" minlength="3" maxlength="15" required>
<!-- 2. Regex Pattern for PAN Card -->
<label for="pancard">PAN Card (e.g. ABCDE1234F):</label>
<input type="text" id="pancard"
pattern="[A-Z]{5}[0-9]{4}[A-Z]{1}"
title="5 uppercase letters, 4 digits, 1 letter" required>
<!-- 3. Numeric Stepper with Step Interval -->
<label for="cgpa">Graduation CGPA (0-10):</label>
<input type="number" id="cgpa" min="0" max="10" step="0.01" required>
<button type="submit" class="demo-btn">Submit Application</button>
</form>
2. The JavaScript Constraint Validation API
When you need custom error messages or dynamic validation logic, HTML5 inputs expose the validity object and validation methods in JavaScript:
| Validity Property | Trigger Condition | Triggering Attribute |
|---|---|---|
validity.valueMissing |
true if a required field is left empty. |
required |
validity.typeMismatch |
true if value doesn't match type format (e.g. invalid email/URL). |
type="email|url" |
validity.patternMismatch |
true if value fails the regular expression regex. |
pattern="..." |
validity.rangeUnderflow / Overflow |
true if value is less than min or greater than max. |
min="..." / max="..." |
validity.tooShort / tooLong |
true if character length violates minlength / maxlength. |
minlength / maxlength |
validity.customError |
true if custom error string set via setCustomValidity(). |
setCustomValidity("...") |
validity.valid |
true ONLY if ALL above validation rules PASS! |
All attributes clean |
const passwordInput = document.querySelector('#password');
const confirmInput = document.querySelector('#confirm-password');
function validatePasswords() {
if (passwordInput.value !== confirmInput.value) {
// Setting ANY non-empty string marks input as INVALID
confirmInput.setCustomValidity('Passwords do not match. Please re-enter.');
} else {
// Passing empty string clears custom error and marks as VALID
confirmInput.setCustomValidity('');
}
}
confirmInput.addEventListener('input', validatePasswords);
3. Modern CSS Validation Pseudo-Classes
CSS provides powerful pseudo-classes that style form inputs dynamically as the user types:
:valid & :invalid
Immediate Evaluation (Flawed UX)
Evaluates on page load. A blank required field is immediately marked :invalid (red borders) before the user even types a single character!
:user-valid & :user-invalid
Modern Gold Standard (Clean UX)
Only triggers after the user has actively typed and unfocused (blurred) the input! Prevents premature red error borders.
/* Modern CSS: Only show green / red styles AFTER user interaction */
input:user-valid {
border-color: #10B981;
background-color: #F0FDF4;
}
input:user-invalid {
border-color: #EF4444;
background-color: #FEF2F2;
}
4. Security Architecture: Client vs Server Validation
🔒 Golden Security Rule: Never Trust Client-Side Validation
• Client-side HTML5 validation is strictly for User Experience (UX) and immediate visual feedback.
• Anyone can open Browser DevTools to remove required, edit pattern, add novalidate to <form>, or submit raw malicious POST requests using curl or Postman.
• Every single validation check MUST be re-verified on the backend server!
5. HTML Form Validation Interview Quiz Deck
Test your knowledge of the Constraint Validation API, regex patterns, and validation pseudo-classes:
🎯 Placement Interview Takeaways
- Q: What is the difference between
checkValidity()andreportValidity()?
Ans:checkValidity()returns a booleantrue/falsesilently without showing any UI popups.reportValidity()evaluates validity AND triggers the native browser validation message popup pointing to the first invalid field. - Q: How do you provide a custom tooltip message for the
patternattribute?
Ans: Add thetitle="..."attribute to the input. The browser will include thetitletext inside its native validation error bubble when the pattern check fails. - Q: Does
novalidatestop JavaScript from validating?
Ans: No.novalidatedisables native browser form submission popups, making it ideal when building custom JavaScript validation UI with custom error toast notifications.