Forms, Validation & Fetch
Prev: Vanilla Interactive Components | Up: tutorials | Next: Progressive Enhancement & Accessibility
Rel: Accessible Forms & Validation, Fetch & Networking
Ref: MDN Web Docs — Using FormData Objects
Tags: #public #web #platform #tutorials #forms
Contents
Constraint Validation API + FormData + fetch()
Enhance a standard HTML <form> by validating with form.checkValidity(), reading fields via new FormData(form), and submitting asynchronously with fetch():
const form = document.querySelector("#profile-form");
const status = document.querySelector("#form-status");
form?.addEventListener("submit", async (event) => {
event.preventDefault();
if (!form.checkValidity()) {
form.reportValidity();
return;
}
const payload = Object.fromEntries(new FormData(form));
status.textContent = "Saving...";
try {
const res = await fetch(form.action, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
status.textContent = "Saved!";
} catch (err) {
status.textContent = `Save failed: ${err.message}`;
}
});
Linked from
- tuts/html
- tuts/html/attributes/form_and_validation_attributes
- tuts/html/elements/forms_and_inputs
- tuts/html/tutorials/accessible_forms_and_validation
- tuts/javascript
- tuts/web/apis/fetch_and_networking
- tuts/web/security/csp_cookies_and_mitigations
- tuts/web/tutorials
- tuts/web/tutorials/forms_validation_and_fetch
- tuts/web/tutorials/progressive_enhancement_and_accessibility
- tuts/web/tutorials/vanilla_interactive_components
Related notes
- tuts/html/tutorials/accessible_forms_and_validation Linked here; links to this page; shared tags: #forms, #tutorials, #web
- tuts/web/tutorials Linked here; links to this page; shared tags: #platform, #tutorials, #web
- tuts/web/tutorials/progressive_enhancement_and_accessibility Linked here; links to this page; shared tags: #platform, #tutorials, #web
- tuts/web/tutorials/vanilla_interactive_components Linked here; links to this page; shared tags: #platform, #tutorials, #web
- tuts/web/apis/fetch_and_networking Linked here; links to this page; shared tags: #platform, #web
- tuts/html/attributes/form_and_validation_attributes links to this page; shared tags: #forms, #web
- tuts/html/elements/forms_and_inputs links to this page; shared tags: #forms, #web
- tuts/web/security/csp_cookies_and_mitigations links to this page; shared tags: #platform, #web
- tuts/html links to this page; shared tags: #web
- tuts/javascript links to this page; shared tags: #web