Lesson 23 of 50JavaScript in the browser
Forms in JavaScript
Handle form submits without a reload, read every field with FormData, and validate with clear, accessible error messages.
Sign-up pages, checkouts, search boxes, settings screens: most of what people do on the web goes through a form. HTML already gives you a lot for free, including labels, keyboard support, and built-in checks like required. JavaScript takes over the parts HTML cannot do alone: sending the data without reloading the page, checks that compare two fields, and error messages that are clear and readable by screen readers. This lesson shows how to do that while keeping everything the browser gives you.
Listen for submit, not click
The most common beginner mistake is putting a click listener on the form's button. It seems to work, until someone presses Enter in a text field, which submits the form without touching the button. The right event is submit on the form element. It fires however the form is sent: a click on the submit button, Enter in a field, or a keyboard user pressing Space on the button.
By default, submitting a form makes the browser send the data to the URL in the form's action attribute and load a new page. To handle it in JavaScript instead, call event.preventDefault() first thing in the listener.
Any way of submitting starts the same process.
Preview
Try submitting with an empty box, then with maya@, then with a real-looking address. The first two never reach your code: the browser blocks them because of required and type="email". Press Enter instead of clicking and notice it still works. A button inside a form is a submit button unless you give it type="button".
submit event rather than on the button's click event?Reading values
Every field has a value property holding its current contents. Two things catch people out:
valueis always a string, even fortype="number"andtype="range". Convert withNumber(input.value), or useinput.valueAsNumber, which gives a number (orNaNif the box is empty).- For checkboxes,
valueis the fixed value from the HTML. Whether it is ticked is inchecked, a boolean.
You can reach fields through form.elements, which lets you look them up by their name attribute: form.elements.email. For a group of radio buttons sharing a name, form.elements.size.value gives the value of the selected one.
What does this print?
const input = document.createElement("input");
input.type = "number";
input.value = "3";
console.log(input.value + 1);FormData: every field at once
Reading fields one by one gets tedious. new FormData(form) collects every field that has a name attribute into one object, using the same rules the browser uses when it sends a form:
data.get("name")returns the value of one field (a string, or aFilefor file inputs).data.getAll("toppings")returns an array, for checkbox groups that share a name.Object.fromEntries(data)turns it into a plain object. Careful: for repeated names it keeps only the last value, so usegetAllfor those.- Fields without a
name, disabled fields, and unticked checkboxes are left out entirely.
Preview
Submit it, then untick every topping and submit again: toppings becomes an empty array. Remove the name from the Name field and it vanishes from the output. Try deleting the toppings: line to see Object.fromEntries keep only one topping.
FormData is also what you send to a server. fetch accepts it directly as the body, which sends it the same way a normal form would (including files). If your API expects JSON instead, send the object you built:
form.addEventListener("submit", async (event) => {
event.preventDefault();
const button = form.querySelector("button");
button.disabled = true; // stop double submits
try {
const response = await fetch("/api/orders", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(Object.fromEntries(new FormData(form))),
});
if (!response.ok) throw new Error(`Server said ${response.status}`);
status.textContent = "Order placed.";
} catch {
status.textContent = "Something went wrong. Please try again.";
} finally {
button.disabled = false;
}
});<input type=checkbox name=terms> that the user leaves unticked. What does new FormData(form).get('terms') return?Validation with the constraint API
HTML attributes give you a lot of validation for free: required, type="email", minlength, maxlength, min, max, step and pattern (a regular expression the value must match). Behind those attributes is the constraint validation API, which JavaScript can read and extend:
| Member | What it does |
|---|---|
field.validity | An object of true or false flags explaining what is wrong |
field.validity.valid | true if every rule passes |
field.validationMessage | The browser's message for the current problem, in the user's language |
field.setCustomValidity("...") | Mark the field invalid with your own message; pass "" to clear it |
form.checkValidity() | true if every field is valid, without showing anything |
form.reportValidity() | Same check, and shows the browser's messages |
The validity flags map to the attributes: valueMissing (required), typeMismatch (type="email" or "url"), tooShort (minlength), patternMismatch (pattern), rangeUnderflow and rangeOverflow (min and max), and customError (you called setCustomValidity).
Match each validity flag to the attribute that triggers it.
setCustomValidity is how you add rules HTML cannot express, like "the two passwords must match". The catch: a custom error stays until you clear it with an empty string, so set it on every input event.
Preview
Type a short password and submit, then two different passwords. The browser shows your custom message in the same bubble as its own. Then change the final "" in checkMatch to "Still wrong", so the message is never cleared, and notice the form can never be submitted again even when the passwords match: that is the classic forgotten-clear bug.
Accessible error messages
The browser's bubbles are a fine start, but they disappear quickly, cannot be styled, and say little about the rule. Most real forms show their own messages next to each field. Doing that well means:
- Add
novalidateto the form. That turns off the bubbles, but the constraint API still works, so you can keep usingvalidity. - Put an error element under each field and connect them with
aria-describedby, so a screen reader reads the message when the field gets focus. - Set
aria-invalid="true"on fields with an error, and remove it once fixed. - On a failed submit, move focus to the first invalid field.
- Write messages that say how to fix the problem: "Enter an email like name@example.com", not "Invalid input".
Preview
Submit the empty form: both messages appear and focus jumps to Name. Fix one field and its message clears as you type, because the last listener (delegated on the whole form) re-checks only fields already marked invalid. That is a good rhythm: do not shout at people while they are still typing, but clear the error the moment it is fixed.
The CSS pseudo-class :user-invalid can style fields red only after the user has interacted with them. It is supported in all current major browsers, but check MDN or Can I Use before relying on it for older ones.
Put the steps of a JavaScript submit handler in order.
- Tap the steps below in the right order.
- submit event
- Fires on a form when it is sent by a button or the Enter key, after built-in validation passes.
- FormData
- An object holding every named, enabled field of a form, built with new FormData(form).
- constraint validation API
- The browser's validation system: validity, validationMessage, setCustomValidity, checkValidity, reportValidity.
- setCustomValidity
- Marks a field invalid with your own message. Passing an empty string clears it.
- novalidate
- A form attribute that turns off the browser's validation bubbles so you can show your own messages.
- aria-describedby
- Links a field to the element that describes it, such as an error message, so screen readers read it out.