How do you choose the correct input type and label?
<form action="/contact" method="post">
<label for="email">Email (required)</label>
<input
id="email"
name="email"
type="email"
autocomplete="email"
required
/>
<label for="reference">Six-digit reference (required)</label>
<input
id="reference"
name="reference"
type="text"
inputmode="numeric"
pattern="[0-9]{6}"
aria-describedby="reference-hint"
required
/>
<p id="reference-hint">Example: 001234</p>
<button type="submit">Send</button>
</form>
A label connected through for and id gives the control an accessible name. name identifies the submitted field; an ID alone does not. autocomplete="email" helps autofill, while inputmode="numeric" suggests a numeric keyboard without validating input. [2][3][4][12]
A six-digit reference is an identifier, not a quantity. A text input preserves the leading zeros in 001234. The pattern restricts a nonempty value to six ASCII digits, while required rejects an empty value. Keep the format hint visible outside the field instead of relying on a disappearing placeholder. [2][3][4][12]
Each example is independent. Put HTML in the document, CSS (if present) in a separate stylesheet, and JavaScript in a file loaded with script type="module" src="...". The /contact and /demo/... paths are illustrative server endpoints, not working services. Examples 2–6 do not send data once their scripts are loaded. In an SPA, call dispose() on unmount; the module checks required element types before registering listeners. Missing elements indicate an integration error, not invalid user input. In an SPA, move the initializer into an imported module without its automatic invocation, call it at each mount and use the returned dispose function (the object method in the date example).
How do native constraints work?
<form id="quantity-form" action="/demo/quantity" method="post">
<label for="quantity">Quantity (1–10)</label>
<input
id="quantity"
name="quantity"
type="number"
min="1"
max="10"
step="1"
required
/>
<button type="button" id="check">Check quantity</button>
<button type="submit">Continue</button>
<p id="quantity-status" role="status"></p>
</form>function initializeQuantityForm() {
const form = document.querySelector("#quantity-form");
const status = document.querySelector("#quantity-status");
if (
!(form instanceof HTMLFormElement) ||
!(status instanceof HTMLElement)
) {
throw new Error("Quantity form markup is incomplete.");
}
const quantity = form.elements.namedItem("quantity");
const checkButton = form.querySelector("#check");
if (
!(quantity instanceof HTMLInputElement) ||
quantity.type !== "number" ||
!(checkButton instanceof HTMLButtonElement)
) {
throw new Error("Quantity controls are missing or invalid.");
}
const lifecycle = new AbortController();
const options = { signal: lifecycle.signal };
function showQuantity() {
status.textContent = "";
if (!form.reportValidity()) {
return;
}
status.textContent = `Valid quantity: ${quantity.valueAsNumber}`;
}
checkButton.addEventListener("click", showQuantity, options);
quantity.addEventListener(
"input",
() => {
status.textContent = "";
},
options,
);
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
showQuantity();
},
options,
);
return () => lifecycle.abort();
}
export const dispose = initializeQuantityForm();
The quantity input accepts integers from 1 to 10. Values 0, 11 and 2.5 violate its constraints. An email input checks address syntax, not mailbox existence. The pattern attribute does not apply to number inputs. [1][12]
checkValidity() returns a boolean and fires invalid for invalid controls; reportValidity() also requests visible browser feedback. valueAsNumber avoids manual parsing but can return NaN when the value is missing or cannot be converted. Check validity before consuming the number. [1][12]
Why does a corrected field remain invalid?
<form id="booking-form" action="/demo/booking" method="post">
<label for="start">Start date (required)</label>
<input id="start" name="start" type="date" required />
<label for="end">End date (required)</label>
<input id="end" name="end" type="date" required />
<button type="submit">Continue</button>
<button type="reset">Reset dates</button>
<p id="booking-status" role="status"></p>
</form>function initializeBookingForm() {
const form = document.querySelector("#booking-form");
const status = document.querySelector("#booking-status");
if (
!(form instanceof HTMLFormElement) ||
!(status instanceof HTMLElement)
) {
throw new Error("Booking form markup is incomplete.");
}
const startDate = form.elements.namedItem("start");
const endDate = form.elements.namedItem("end");
if (
!(startDate instanceof HTMLInputElement) ||
!(endDate instanceof HTMLInputElement) ||
startDate.type !== "date" ||
endDate.type !== "date"
) {
throw new Error("Booking dates are missing or invalid.");
}
const lifecycle = new AbortController();
const options = { signal: lifecycle.signal };
let resetTimer;
function validateDateRange() {
endDate.setCustomValidity("");
if (!startDate.value || !endDate.value) {
return;
}
if (endDate.valueAsNumber < startDate.valueAsNumber) {
endDate.setCustomValidity(
"Choose an end date on or after the start date.",
);
}
}
function handleDateChange() {
status.textContent = "";
validateDateRange();
}
for (const field of [startDate, endDate]) {
field.addEventListener("input", handleDateChange, options);
field.addEventListener("change", handleDateChange, options);
}
form.addEventListener(
"reset",
() => {
endDate.setCustomValidity("");
status.textContent = "";
clearTimeout(resetTimer);
resetTimer = setTimeout(validateDateRange, 0);
},
options,
);
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
validateDateRange();
if (!form.reportValidity()) {
return;
}
status.textContent = "Date range is valid.";
},
options,
);
validateDateRange();
return {
validateDateRange,
dispose() {
lifecycle.abort();
clearTimeout(resetTimer);
endDate.setCustomValidity("");
},
};
}
export const { validateDateRange, dispose } = initializeBookingForm();
A rule involving two fields needs more than required. A booking end date must not precede its start date. Compare the date controls using valueAsNumber rather than locale-formatted strings. [1]
A nonempty custom validity message keeps a control invalid even after editing. Clear it with an empty string before rechecking. Listen to both dates, and explicitly call the validator after programmatic changes. Native required constraints handle missing dates. [1]
reset() does not clear custom validity messages. The example clears the message and rechecks the range after the initial values are restored. After setting dates in code, call the exported validateDateRange() before requestSubmit(), because a stale error can prevent the submit event itself. [1][9][13]
How do you make validation errors accessible?
<form id="profile-form" action="/demo/profile" method="post">
<label for="profile-email">Email (required)</label>
<input
id="profile-email"
class="profile-form__email"
name="email"
type="email"
autocomplete="email"
aria-describedby="email-error"
required
/>
<p id="email-error" class="profile-form__error" hidden></p>
<button type="submit">Check email</button>
<p id="profile-status" role="status"></p>
</form>.profile-form__email[aria-invalid="true"] {
border: 2px solid currentColor;
}
.profile-form__error {
font-weight: 600;
}function initializeProfileForm() {
const form = document.querySelector("#profile-form");
const error = document.querySelector("#email-error");
const status = document.querySelector("#profile-status");
if (
!(form instanceof HTMLFormElement) ||
!(error instanceof HTMLElement) ||
!(status instanceof HTMLElement)
) {
throw new Error("Profile form markup is incomplete.");
}
const email = form.elements.namedItem("email");
if (!(email instanceof HTMLInputElement) || email.type !== "email") {
throw new Error("Profile email field is missing or invalid.");
}
const lifecycle = new AbortController();
const options = { signal: lifecycle.signal };
const originalNoValidate = form.noValidate;
function clearError() {
email.removeAttribute("aria-invalid");
error.hidden = true;
error.textContent = "";
}
function validateEmail() {
if (email.validity.valid) {
clearError();
return true;
}
email.setAttribute("aria-invalid", "true");
error.textContent = email.validity.valueMissing
? "Enter your email address."
: "Enter an email address such as name@example.com.";
error.hidden = false;
return false;
}
function handleSubmit(event) {
event.preventDefault();
status.textContent = "";
if (!validateEmail()) {
if (document.activeElement === email) {
status.textContent = error.textContent;
} else {
email.focus();
}
return;
}
status.textContent = "Email format is valid. No data has been sent.";
}
form.addEventListener("submit", handleSubmit, options);
email.addEventListener(
"input",
() => {
status.textContent = "";
if (email.hasAttribute("aria-invalid")) {
validateEmail();
}
},
options,
);
form.addEventListener(
"reset",
() => {
clearError();
status.textContent = "";
},
options,
);
form.noValidate = true;
return () => {
lifecycle.abort();
clearError();
form.noValidate = originalNoValidate;
};
}
export const dispose = initializeProfileForm();
A red border cannot explain what went wrong. Identify the field, describe the problem and suggest a valid format. The example associates the message with the input through aria-describedby, sets aria-invalid only after validation fails and uses a role="status" region for feedback. [5][6]
Set noValidate only after installing the custom handlers, retaining native validation if JavaScript is unavailable. Focus the invalid field without discarding the entered value. This demo checks format only; it does not save a profile. A real multi-field form must validate every constraint, provide an error summary and preserve input when the server rejects it. [5][6]
The field error remains visible until corrected; focus moves to the invalid field. If the field already has focus, the status region receives the message instead. This reduces duplicate announcements. The CSS is separate, and text conveys the error rather than color alone. dispose() removes listeners and restores the original noValidate state. [5][6]
Why are values missing from FormData?
<form id="preferences-form" action="/demo/preferences" method="post">
<label for="account-id">Account</label>
<input id="account-id" name="accountId" value="A-42" readonly />
<label for="plan">Plan</label>
<input id="plan" name="plan" value="basic" disabled />
<fieldset>
<legend>Topics</legend>
<label>
<input type="checkbox" name="topics" value="css" checked />
CSS
</label>
<label>
<input type="checkbox" name="topics" value="js" checked />
JavaScript
</label>
</fieldset>
<button type="submit" name="intent" value="save">Preview preferences</button>
</form>function initializePreferencesForm() {
const form = document.querySelector("#preferences-form");
if (!(form instanceof HTMLFormElement)) {
throw new Error("Preferences form is missing.");
}
const lifecycle = new AbortController();
function handleSubmit(event) {
event.preventDefault();
const data = event.submitter
? new FormData(form, event.submitter)
: new FormData(form);
const preferences = {
accountId: data.get("accountId"),
topics: data.getAll("topics"),
intent: data.get("intent"),
};
console.log(preferences);
console.log(data.has("plan")); // false
}
form.addEventListener("submit", handleSubmit, { signal: lifecycle.signal });
return () => lifecycle.abort();
}
export const dispose = initializePreferencesForm();
FormData collects entries from controls that participate in submission. Disabled controls and unchecked checkboxes are omitted; supported read-only fields still submit their values. The example includes accountId and two topics, but no plan entry. [7]
get() returns the first matching value; getAll() preserves repeated keys. Object.fromEntries(data) loses earlier entries with the same key. Passing event.submitter includes the activated button's name and value. None of disabled, readonly or hidden fields is an authorization boundary; clients can modify requests. [7]
Why does form.submit() bypass validation?
<form id="draft-form" action="/demo/draft" method="post">
<label for="title">Title (required)</label>
<input id="title" name="title" required />
<button id="publish" type="submit" name="intent" value="publish">
Publish
</button>
<button id="toolbar-publish" type="button" hidden>
Publish from toolbar
</button>
</form>function initializeDraftForm() {
const form = document.querySelector("#draft-form");
if (!(form instanceof HTMLFormElement)) {
throw new Error("Draft form is missing.");
}
const publishButton = form.querySelector("#publish");
const toolbarButton = form.querySelector("#toolbar-publish");
if (
!(publishButton instanceof HTMLButtonElement) ||
publishButton.type !== "submit" ||
publishButton.form !== form ||
!(toolbarButton instanceof HTMLButtonElement) ||
toolbarButton.type !== "button"
) {
throw new Error("Draft form buttons are missing or invalid.");
}
const lifecycle = new AbortController();
const options = { signal: lifecycle.signal };
toolbarButton.addEventListener(
"click",
() => {
form.requestSubmit(publishButton);
},
options,
);
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
const data = event.submitter
? new FormData(form, event.submitter)
: new FormData(form);
console.log(data.get("intent")); // publish
},
options,
);
toolbarButton.hidden = typeof form.requestSubmit !== "function";
return () => {
lifecycle.abort();
toolbarButton.hidden = true;
};
}
export const dispose = initializeDraftForm();
Handle the form's submit event instead of listening only for clicks so keyboard submission is covered. form.submit() skips constraint validation and the submit event; requestSubmit() follows the normal submit-button procedure, respecting its options. [9]
The toolbar invokes requestSubmit(publishButton). An empty title blocks submission, and a valid one allows the handler to read intent=publish. Avoid naming a control submit, which can shadow the form method. Use novalidate and formnovalidate deliberately rather than to hide validation failures. [9]
How do you submit data safely and handle server errors?
<form
id="feedback-form"
action="/api/feedback"
method="post"
enctype="multipart/form-data"
>
<label for="message">Message (required)</label>
<textarea
id="message"
name="message"
maxlength="1000"
aria-describedby="message-hint"
required
></textarea>
<p id="message-hint">Maximum 1000 characters.</p>
<p id="message-error" hidden></p>
<button type="submit">Send feedback</button>
</form>
<p id="feedback-status" role="status"></p>function initializeFeedbackForm() {
const form = document.querySelector("#feedback-form");
const status = document.querySelector("#feedback-status");
const error = document.querySelector("#message-error");
if (
!(form instanceof HTMLFormElement) ||
!(status instanceof HTMLElement) ||
!(error instanceof HTMLElement)
) {
throw new Error("Feedback form markup is incomplete.");
}
const message = form.elements.namedItem("message");
const sendButton = form.querySelector('button[type="submit"]');
if (
!(message instanceof HTMLTextAreaElement) ||
!(sendButton instanceof HTMLButtonElement)
) {
throw new Error("Feedback form controls are missing or invalid.");
}
const endpoint = new URL(form.action);
if (endpoint.origin !== window.location.origin) {
throw new Error("Feedback endpoint must be same-origin.");
}
const lifecycle = new AbortController();
const options = { signal: lifecycle.signal };
const originalDescription = message.getAttribute("aria-describedby");
let isSubmitting = false;
function clearError() {
message.removeAttribute("aria-invalid");
message.setAttribute(
"aria-describedby",
originalDescription ?? "message-hint",
);
error.hidden = true;
error.textContent = "";
}
function showFieldError() {
error.textContent = "The server rejected this message. Review its content.";
error.hidden = false;
message.setAttribute("aria-invalid", "true");
message.setAttribute("aria-describedby", "message-hint message-error");
}
async function handleSubmit(event) {
event.preventDefault();
if (isSubmitting) {
return;
}
if (!form.reportValidity()) {
return;
}
clearError();
isSubmitting = true;
sendButton.setAttribute("aria-disabled", "true");
status.textContent = "Sending feedback...";
try {
const data = event.submitter
? new FormData(form, event.submitter)
: new FormData(form);
const submittedMessage = data.get("message");
const response = await fetch(endpoint, {
method: "POST",
body: data,
credentials: "same-origin",
redirect: "error",
signal: lifecycle.signal,
});
if (lifecycle.signal.aborted) {
return;
}
if (response.status === 422) {
if (message.value === submittedMessage) {
showFieldError();
status.textContent = error.textContent;
} else {
status.textContent =
"The previous message was rejected. Your edits are preserved.";
}
return;
}
if (response.status === 202) {
status.textContent =
"Message accepted for processing, not yet confirmed as saved.";
return;
}
if (![200, 201, 204].includes(response.status)) {
status.textContent =
`Delivery not confirmed (HTTP ${response.status}). Check before retrying.`;
return;
}
status.textContent = message.value === submittedMessage
? "Feedback sent."
: "Previous message sent. Your newer edits have not been sent.";
} catch {
if (!lifecycle.signal.aborted) {
status.textContent = "Delivery could not be confirmed. Check before retrying.";
}
} finally {
isSubmitting = false;
sendButton.removeAttribute("aria-disabled");
}
}
form.addEventListener("submit", handleSubmit, options);
message.addEventListener(
"input",
() => {
clearError();
if (!isSubmitting) {
status.textContent = "";
}
},
options,
);
return () => {
lifecycle.abort();
sendButton.removeAttribute("aria-disabled");
clearError();
status.textContent = "";
};
}
export const dispose = initializeFeedbackForm();
The example posts FormData to the illustrative same-origin endpoint /api/feedback. The browser supplies the multipart boundary. aria-disabled communicates the pending state without removing button focus, while isSubmitting actually prevents repeated submissions. The request captures a snapshot of the data; later edits are retained. finally allows another attempt, and dispose() aborts the request and removes listeners. [8][14]
The demo API contract is explicit: 200, 201 or 204 confirm a save; 202 means accepted for processing; 422 means server validation rejected the message field. On 422, mark the field only if it still contains the submitted value. Other statuses and network errors do not confirm persistence; do not automatically retry. The example rejects redirects and requires a same-origin endpoint. The server independently validates data, authorization and business rules. For cookie sessions, the server must provide and verify an appropriate CSRF token, for example in a hidden form field, according to its chosen strategy. Critical operations require server-side idempotency. The backend is not included. [8][10][11][14][15]
