Form processing
Form processing in JavaScript means taking control of what happens when a user submits a form: stopping the default page reload when needed, reading the values, checking them, showing helpful errors and then sending the data to a server, usually with fetch. It turns a plain HTML form into a smooth experience where the user gets feedback without losing what they typed.
Listen to submit, not to the button
Attach your handler to the form's submit event rather than the button's click. Submit fires whether the user clicks the button or presses Enter in a field, and it only fires after the browser's own validation (from attributes like required and type="email") passes.
<form id="signup" novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<label for="password">Password</label>
<input id="password" name="password" type="password" minlength="8" required>
<label><input name="terms" type="checkbox"> I accept the terms</label>
<p id="form-error" role="alert"></p>
<button type="submit">Create account</button>
</form>
Reading values with FormData
FormData collects every named field in one step. Fields without a name attribute are skipped, and an unchecked checkbox is simply missing.
const form = document.getElementById('signup');
const errorBox = document.getElementById('form-error');
form.addEventListener('submit', async (event) => {
event.preventDefault();
errorBox.textContent = '';
if (!form.checkValidity()) {
form.reportValidity();
return;
}
const data = Object.fromEntries(new FormData(form));
if (!data.terms) {
errorBox.textContent = 'Please accept the terms to continue.';
return;
}
const button = form.querySelector('button[type="submit"]');
button.disabled = true;
try {
const res = await fetch('/api/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: data.email, password: data.password }),
});
if (!res.ok) throw new Error('Sign-up failed. Please try again.');
form.reset();
errorBox.textContent = 'Account created.';
} catch (err) {
errorBox.textContent = err.message;
} finally {
button.disabled = false;
}
});
Here novalidate turns off the automatic browser bubbles so the script decides when to show them, using checkValidity() and reportValidity().
Layers of validation
- HTML attributes such as
required,minlength,patternandtypegive basic checks for free. - JavaScript checks handle rules HTML cannot express, like "passwords must match".
- Server validation is mandatory, because anyone can bypass the browser and send a request directly.
For custom messages on a single field, input.setCustomValidity('message') marks it invalid; call it with an empty string to clear the error.
Mistakes when processing forms
Forgetting event.preventDefault() is the most common one. The page reloads, your fetch is cancelled and the console clears, so it looks like nothing happened. If your handler is async, call preventDefault() at the very top, before any await.
A second is reading values as numbers without converting them. Every value from a form is a string, so '2' + '3' gives '23'. Use Number() or input.valueAsNumber.
A third is not disabling the button during the request, which lets impatient users submit twice and create duplicate records. Re-enable it in finally so it recovers after errors.
Making errors accessible
Show errors as text near the field, not only as a red border. A container with role="alert" announces messages to screen reader users, and setting aria-invalid="true" on a bad field tells assistive technology which one needs fixing.
Resetting the form deserves care as well. form.reset() returns every field to its initial value from the HTML, but it does not touch messages you wrote into the page yourself. Clear your own error text at the same time, or a stale message will stay on screen after a successful submit. If the request fails, keep the user's input rather than resetting, so they only fix what was wrong.
Recap
Handle submit, call preventDefault() first, read fields with FormData, validate in layers, disable the button while sending and always validate again on the server.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.