The previous lesson in this module showed you how one listener can serve a whole list of items. This lesson takes that idea into the place where people actually type things, because a form is where a mistake costs real money. Handling a form in JavaScript is really two separate jobs. You have to get the values out, and then you have to decide whether they are acceptable. The browser gives you a proper tool for each of those jobs, and using them together is what separates a form that guides somebody from a form that quietly accepts nonsense and fails later on the server. The next lesson in this module looks at updating a list on the screen without rewriting the whole page.
This is the first lesson in the Vanilla JavaScript Projects module, and the next lesson in this module is about "Updating Lists of Content Without Rewriting Everything".
How do you read the values out of a form?
There are three ways to do it, and they suit different situations. You can reach for a single control by its id and read its value, which is fine when you know exactly which field you want. You can walk the form.elements collection, which gives you every control by name in one place. Or you can build a FormData object, which produces exactly the values that the browser would send if the form were submitted normally.
The last option is the one to reach for by default. FormData understands the fiddly parts of form behaviour for you. A checkbox that nobody ticked is left out completely. A radio group contributes only its checked member. A disabled control is skipped. Writing those rules by hand is how you end up submitting "on" for checkboxes that nobody ever touched.
<form id="order" novalidate>
<label for="customer">Name</label>
<input id="customer" name="customer" type="text" required>
<label for="qty">Quantity</label>
<input id="qty" name="qty" type="number" min="1" max="10" value="2">
<label><input type="checkbox" name="gift" value="yes"> Gift wrap</label>
<label><input type="checkbox" name="gift" value="card"> Add a card</label>
<label><input type="radio" name="plan" value="basic" checked> Basic</label>
<label><input type="radio" name="plan" value="pro"> Pro</label>
<p id="customer-error" class="error"></p>
<button type="submit">Place order</button>
</form>
const form = document.querySelector("#order");
const data = new FormData(form);
console.log(data.get("customer")); // "" because the field is empty
console.log(data.get("qty")); // "2"
console.log(data.get("plan")); // "basic" because that radio is checked
console.log(data.get("gift")); // null because no gift box is ticked
console.log(data.getAll("gift")); // [] because no gift box is ticked
console.log(data.has("customer")); // true
Two things are worth noticing here. Every value comes back as a string, because a form submission only contains text. And the key list has size twice when a multiple select is used, once for each selected option, which is the correct behaviour for that control.
How do checkbox and radio groups that share a name behave?
Controls that share the same name form a group, and the way you read a group depends on how many answers are possible. get returns only the first match, which is exactly what you want for a radio group and a mistake for a checkbox group. getAll returns every match as an array, and that is the correct call whenever more than one box can be ticked.
const form = document.querySelector("#order");
// Tick both gift options.
form.querySelector('[name="gift"][value="yes"]').checked = true;
form.querySelector('[name="gift"][value="card"]').checked = true;
const data = new FormData(form);
console.log(data.getAll("gift")); // ["yes", "card"]
console.log(data.get("gift")); // "yes" because get only returns the first
// Radio buttons are mutually exclusive, so only the checked one appears.
form.querySelector('[name="plan"][value="pro"]').checked = true;
console.log(new FormData(form).getAll("plan")); // ["pro"]
One shortcut needs a warning label. Object.fromEntries(new FormData(form)) turns the form into a plain object in a single line, which is wonderfully convenient. It is also dangerous when two controls share a name, because the later one quietly overwrites the earlier one. For the gift group above, the resulting object would contain only gift: "card". Use getAll whenever names are repeated, and check the shape of your data before you trust it.
How do I read a number input without getting a string?
Every value that comes out of the DOM is a string, and that includes the value of type="number". The dedicated property for a numeric field is valueAsNumber. It gives you a real number when the field holds a valid number, and it gives you NaN when it does not, which includes the case where the field is completely empty. That distinction matters, because an empty quantity is not zero, and treating it as zero is how an order ships the wrong number of items.
const qty = document.querySelector("#qty");
console.log(qty.value); // "2" because the DOM gives you a string
console.log(qty.valueAsNumber); // 2
console.log(typeof qty.valueAsNumber); // "number"
qty.value = "";
console.log(qty.value); // ""
console.log(qty.valueAsNumber); // NaN because an empty field is not zero
The same idea applies to a checkbox. checkbox.checked gives you a boolean, while checkbox.value gives you the string inside the value attribute, which often means nothing to a person. Read checked for the answer, and read value for the detail.
How does the browser's built-in constraint validation work?
Modern browsers validate forms on their own. Attributes such as required, min, max, step, and pattern, together with the type of the input itself (email, url, number), all express a rule, and the browser checks them before the form is allowed to submit.
Two interfaces let you run those checks yourself. form.checkValidity() returns a single boolean for the whole form. Each control also has a validity object with one flag for each kind of failure, such as valueMissing, typeMismatch, rangeOverflow, rangeUnderflow, and patternMismatch, together with valid and customError. The validationMessage property holds the wording that the browser itself uses for the problem.
const form = document.querySelector("#order");
const customer = document.querySelector("#customer");
const qty = document.querySelector("#qty");
console.log(customer.validity.valueMissing); // true because a required field is empty
console.log(form.checkValidity()); // false
customer.value = "Priya";
console.log(customer.validity.valueMissing); // false
console.log(form.checkValidity()); // true
qty.value = "99";
console.log(qty.validity.rangeOverflow); // true because 99 is past max="10"
console.log(qty.validity.rangeUnderflow); // false
console.log(form.checkValidity()); // false
Reading the individual flags is more useful than the single boolean, because it tells you which rule failed. That is exactly what you need in order to put the right message next to the right field.
How do I add a validation rule the browser does not know about?
The built-in rules cover format and range, but they do not cover business rules. A rule like "the customer name must include a surname" needs setCustomValidity. Give it a message and the control becomes invalid. Give it an empty string and the custom message is cleared. The customError flag tells you whether a custom message is currently in force.
const form = document.querySelector("#order");
const customer = document.querySelector("#customer");
customer.value = "Priya";
// A rule that the browser has no built-in opinion about.
customer.setCustomValidity("Customer name must include a surname");
console.log(customer.validationMessage); // "Customer name must include a surname"
console.log(customer.validity.customError); // true
console.log(form.checkValidity()); // false
// An empty string clears the custom message.
customer.setCustomValidity("");
console.log(customer.validity.customError); // false
console.log(form.checkValidity()); // true
Two practical rules come with this. Clear the custom message as soon as the person edits the field, because a stale error message sticks around long after the problem has been fixed, and listening for the input event is the usual way to do that. And remember that client-side validation is a convenience rather than a security control. Anybody can bypass a check that only runs in the browser, so the server has to validate every value again.
How should a validation error be shown to the person filling in the form?
Putting red text next to a field is only half of the job. A person who uses a screen reader has to be told that the field is invalid and what the message says, and that takes two attributes. Put aria-invalid="true" on the control, and put aria-describedby on it as well, pointing at the element that holds the message. The message element itself is often given role="alert" so that it is announced when it appears. Moving the focus to the first invalid control is the other half, because a keyboard user who submits an invalid form otherwise has no idea where the problem is.
const form = document.querySelector("#order");
const customer = document.querySelector("#customer");
const error = document.querySelector("#customer-error");
function showError(message) {
error.textContent = message;
customer.setCustomValidity(message);
customer.setAttribute("aria-invalid", message ? "true" : "false");
}
// Re-check while the person is typing so that the error clears itself.
customer.addEventListener("input", function () {
showError(customer.value.trim() ? "" : "Please enter a customer name");
});
form.addEventListener("submit", function (event) {
event.preventDefault();
showError(customer.value.trim() ? "" : "Please enter a customer name");
if (!form.checkValidity()) {
customer.focus();
return;
}
const data = new FormData(form);
console.log("customer:", data.get("customer"));
console.log("qty:", data.get("qty"));
console.log("plan:", data.get("plan"));
});
The example form carries novalidate, which turns off the browser's own blocking bubble so that your custom messages can take over. If you would rather keep the native bubbles, call reportValidity() instead of checkValidity(), because it both checks the form and shows the browser's own message on the control that caused the problem.
The form handling reference
new FormData(form)gives you exactly the values that the browser would submit.data.get(name),data.getAll(name),data.has(name), and[...data.entries()]let you read one value, many values, or the whole set.input.valueAsNumberandinput.checkedgive you typed and boolean state instead of strings.form.checkValidity(), together with flags such aselement.validity.valueMissing, tells you what the browser thinks of the data.element.setCustomValidity(message)adds a rule of your own, and passing an empty string clears it.aria-invalid,aria-describedby, androle="alert"make the error visible to assistive technology.
Try it yourself: write a form with a text field for a username, a number field for an age that has min="18", and a checkbox for "accept terms" that has required. Attach a submit handler that calls preventDefault(), and then console.log the result of form.checkValidity() together with the validity flags of each control. Leave the form empty, submit it, and note which flags are set. Then type a valid age, tick the box, and watch checkValidity() change to true. Finish by adding a setCustomValidity rule that rejects any username containing a space.