Forms + JavaScript
Chapter 1 of this course covered native browser validation (required, pattern, etc.) — entirely declarative, no JavaScript needed. This chapter covers where JavaScript genuinely adds value on top of that: custom validation messages, validating logic too complex for built-in attributes alone, and reading a form's data without manually grabbing every field one at a time.
The Constraint Validation API — JavaScript Meets Built-In Validation
Every form-related element exposes methods and properties that hook directly into the native validation from Chapter 1, rather than replacing it entirely.
| Property/Method | What it does |
|---|---|
| .checkValidity() | Returns true/false — does this field currently satisfy its built-in constraints? |
| .validity | A detailed object describing exactly WHY it's invalid (valueMissing, patternMismatch, tooShort, etc.) |
| .setCustomValidity(msg) | Overrides the browser's default error message with your own custom text |
| .reportValidity() | Triggers the native validation UI to display immediately, as if the form had been submitted |
setCustomValidity(''). Forgetting this step is the single most common bug with this API, leaving a field permanently marked invalid even when its actual value is now correct.
Validation Beyond What Built-In Attributes Can Express
Some rules genuinely can't be expressed with pattern or min/max alone — comparing two fields against each other is the classic example.
FormData — Reading Submitted Values Without Grabbing Each Field
Rather than manually querying every input by ID and reading .value one at a time, FormData reads an entire form's submittable values at once, keyed by each field's name attribute (the exact attribute Fundamentals Chapter 7 established as essential for submission).
Sending FormData Without a Page Reload
Passing a FormData object directly as a fetch request's body automatically sets the correct content type and encoding, including any file inputs (Fundamentals Chapter 5's type="file") — no manual serialisation needed.
Chapter 10 Quick Reference
- checkValidity()/validity/setCustomValidity()/reportValidity() — hook into native validation rather than replacing it
- Always clear setCustomValidity('') once a field becomes valid again — the most common bug with this API
- Use JS validation for logic built-in attributes can't express — comparing two fields, cross-field rules
- FormData — reads all submittable values at once, keyed by each field's name attribute
- new FormData(form) passed directly as a fetch body — handles encoding and file uploads automatically
- Client-side JS validation is still bypassable — server-side validation of every value remains required regardless
- Next chapter: web components intro — custom elements & shadow DOM basics, the lead-in to Course 3