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.

01

Presence & Length

Character Thresholds

  • required: Blocks submission if field is empty or unselected.
  • minlength="8": Minimum character count.
  • maxlength="30": Prevents typing beyond limit.
02

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).
03

Pattern Matching (Regex)

Strict Format Matching

  • pattern="[0-9]{10}": 10-digit mobile number.
  • title="...": Custom hint shown in native tooltip when pattern fails.
HTML Source Code validation-form.html
<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>
Rendered Browser Output ● Live Preview

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
Custom Validation with setCustomValidity
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:

01

: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!

02

: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.

Clean User Interaction CSS Styling
/* 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:

🎯 Form Validation Interview Deck
Question 1 of 5
⭐ Standard • Form Attributes novalidate Attribute
Which attribute on <form> disables all native HTML5 client-side validation popups upon submission?
A) bypass-validation="true"
B) novalidate
C) skip-check
D) validate="none"
⭐ High Frequency • JS API setCustomValidity
How do you clear a custom error message and mark an input as VALID using JavaScript's Constraint Validation API?
A) input.setCustomValidity(null)
B) input.setCustomValidity('') (pass empty string)
C) input.validity.customError = false
D) input.clearError()
⭐ Modern CSS • UX :user-invalid vs :invalid
What UX problem does the modern CSS :user-invalid pseudo-class solve over standard :invalid?
A) It prevents empty required fields from rendering red error styles before the user has even touched them.
B) It auto-corrects typos in email addresses.
C) It disables form submission in Safari.
D) It converts input values to uppercase automatically.
⭐ JS API • Validity State valueMissing Property
Which property on input.validity is true when a required input field is left completely empty?
A) validity.isEmpty
B) validity.requiredError
C) validity.valueMissing
D) validity.blankField
⭐ Architecture • Security Server Validation Defense
Why must backend servers ALWAYS re-validate incoming form data even if HTML5 client validation is perfect?
A) Because HTML5 validation only works on Chrome, not Firefox.
B) Because client-side HTML validation can easily be bypassed or stripped via DevTools, scripts, or direct curl API requests.
C) Client validation slows down database indexing.
D) HTML forms encrypt all data before sending to server.

🎯 Placement Interview Takeaways

  • Q: What is the difference between checkValidity() and reportValidity()?
    Ans: checkValidity() returns a boolean true/false silently 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 pattern attribute?
    Ans: Add the title="..." attribute to the input. The browser will include the title text inside its native validation error bubble when the pattern check fails.
  • Q: Does novalidate stop JavaScript from validating?
    Ans: No. novalidate disables native browser form submission popups, making it ideal when building custom JavaScript validation UI with custom error toast notifications.