FormData, submit Events, and Client-Side Checks
Lesson 13 of 38 in the JavaScript learning path.
How do I read a form with FormData and stop a bad submit?
The submit event fires when the student activates a submit button or presses Enter in a field. preventDefault stops the browser from navigating to the form action, which is what you want when the page should show a result in place. FormData reads the successful controls by name: text fields, the selected option, and a checked checkbox. Unchecked checkboxes are omitted, so a missing notify key means the box was off.
Client checks are a convenience, not a security boundary. reportValidity shows the built-in messages for required fields, and setCustomValidity adds a message when the trimmed name is shorter than two characters. After the values look usable, the script still cancels the navigation and writes them with textContent. The server must validate again, because a modified request can skip every check that ran in the browser. The sample posts nowhere. It only proves the values you would send.
Syntax & Parameters
form.addEventListener("submit", (event) => {
event.preventDefault();
const data = new FormData(form);
form.reportValidity();
});
Example
Interactive preview available'use strict';
const form = document.querySelector('#comment-form');
const result = document.querySelector('#form-result');
function show(message) {
if (result !== null) result.textContent = message;
console.log(message);
}
function namedControl(name) {
if (!(form instanceof HTMLFormElement)) return null;
const control = form.elements.namedItem(name);
if (control instanceof HTMLInputElement) return control;
if (control instanceof HTMLTextAreaElement) return control;
if (control instanceof HTMLSelectElement) return control;
return null;
}
if (form instanceof HTMLFormElement) {
form.addEventListener('input', (event) => {
const target = event.target;
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
target.setCustomValidity('');
}
});
form.addEventListener('submit', (event) => {
const data = new FormData(form);
const name = String(data.get('displayName') ?? '').trim();
const lesson = String(data.get('lesson') ?? '').trim();
const body = String(data.get('body') ?? '').trim();
const notify = data.get('notify') === 'on' ? 'yes' : 'no';
const nameInput = namedControl('displayName');
if (name.length < 2 && nameInput !== null) {
event.preventDefault();
nameInput.setCustomValidity('Enter at least 2 characters.');
nameInput.reportValidity();
show('Submit stopped: name is too short.');
return;
}
if (nameInput !== null) nameInput.setCustomValidity('');
if (!form.reportValidity()) {
event.preventDefault();
show('Submit stopped: the form is not valid.');
return;
}
event.preventDefault();
show([
`displayName: ${name}`,
`lesson: ${lesson}`,
`notify: ${notify}`,
`body: ${body}`,
'The server must validate again.',
].join('\n'));
});
}
show('Form listener attached. The server must validate again.');
Expected Output
On load, #form-result: Form listener attached. The server must validate again. After submitting Amina, lesson js-form-submit, notify checked, and the body "The form kept my comment as text.": displayName: Amina lesson: js-form-submit notify: yes body: The form kept my comment as text. The server must validate again. After submitting a one-character name: Submit stopped: name is too short.
Line-by-Line Walkthrough
- The script selects the comment form and the result region, then show writes a message with textContent and prints it.
- namedControl returns the input, textarea, or select for a name, or null when the form or the control is missing.
- The input listener clears custom validity as the student edits, so an old short-name message does not stick.
- On submit, FormData reads displayName, lesson, body, and the notify checkbox. A missing checkbox value becomes no.
- The name is trimmed. Fewer than two characters sets a custom message, calls reportValidity, cancels the submit, and returns.
- A long enough name clears the custom message before the built-in checks run.
- reportValidity covers required fields and minlength. A false result cancels the navigation and logs that the form is not valid.
- A valid submit still calls preventDefault so the browser does not leave the page for the form action.
- The result lists the trimmed values as text, plus a reminder that the server must validate again.
- On load the script logs that the listener is attached and repeats that server-side validation is required.
Common Pitfalls & Security
Client-side checks improve the form. They do not protect the server. Anyone can skip the browser and post displayName, lesson, and body directly to the action URL. The server must validate again, authorize the student, and store the comment with a query that treats the body as data. Showing the values with innerHTML would also parse them. A body equal to the untrusted string <img src="x" alt="untrusted"> assigned with result.innerHTML = body becomes an image and is an XSS hole.
- Forgetting preventDefault on a valid submit navigates to action and the in-page result disappears.
- FormData omits unchecked checkboxes and disabled fields. Do not treat a missing key as a tamper signal by itself.
- setCustomValidity blocks submit until you clear it. Clear the message on input or the student cannot recover.
- minlength counts characters before trim. A name of spaces can pass the attribute and fail the trimmed check, so keep both.
- Trusting the lesson slug from the select is fine for display and not fine for access control. The server decides which lesson accepts the comment.
Best Practices & Modern Standards
Use the constraint validation API for required fields and reportValidity so the browser shows the message next to the control. Add setCustomValidity for rules HTML does not express well, such as a trimmed length. Always preventDefault when you handle the result in the page. ES2024 does not move validation to the client permanently. The server remains the authority.
Read controls with FormData rather than a pile of one-off value reads, and render the echo with textContent. Keep the submit button as type submit so Enter works. Pair this page with a real POST later, and send the same field names the server expects. Log a reminder in the sample output that the browser check is not the last check.
Real-World Use
A lesson page ends with a comment form. The student enters a name, picks the lesson, writes a note, and optionally asks for email. Submit builds FormData, rejects a one-letter name, and otherwise shows the values in a confirmation region without leaving the page. The confirmation is text, so a note that contains a tag stays visible as characters.
The action still points at the comment endpoint the server owns. In production the same payload is sent after the local check, and the server repeats every rule, escapes the body on the way into storage, and ignores a lesson slug the student is not allowed to post on. The browser message is only the fast feedback.
Frequently Asked Questions
Why call preventDefault if the form is valid?
Without it the browser navigates to the action URL and unloads the page. This sample wants to show the values in place. A production page can preventDefault and then send the same FormData with fetch.
Does reportValidity replace a server check?
No. It only helps the person using this browser. A request built outside the page skips it. The server must validate again, including length, allowed lesson ids, and the signed-in user.
How do I know a checkbox was checked?
FormData includes a checkbox only when it is checked. This form uses the default value on, so data.get("notify") === "on" means yes. Any other result, including null, means the box was off.
Why not display the comment with innerHTML?
The comment is untrusted text. innerHTML would parse tags inside it and open an XSS hole. textContent shows the characters the student typed, which is what a confirmation region should do.