DOM Forms
JavaScript DOM Forms: Reading Values and Validating Submissions
JavaScript DOM forms work by listening for the submit event, stopping the browser's default page reload with event.preventDefault(), and reading the input values through FormData or direct element references. This lesson shows how to collect every field at once, validate input with the browser's built-in tools, and avoid the mistakes that most often break form code.
Handling the Submit Event
Attach your handler to the form's submit event, not to the button's click event. Users often submit by pressing Enter inside a text field, and only the submit event catches both that and a button click:
const form = document.getElementById("contact-form");
form.addEventListener("submit", (event) => {
event.preventDefault(); // stop the full page reload
// read and send the data here
});Without preventDefault(), the browser sends a traditional request and reloads the page, which is not what you want when you plan to send the data with fetch() and update the page yourself.
Reading All Fields at Once with FormData
Instead of querying ten inputs one by one, pass the form into new FormData(form). It collects every named field automatically. Object.fromEntries(formData) then turns the result into a plain object that is ready to send as JSON. You can use our JSON Formatter to format and validate JSON data.
form.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const payload = Object.fromEntries(formData);
console.log(payload); // { email: "...", age: "22" }
});All values arrive as strings, so convert numbers yourself, for example with Number(payload.age).
Client-Side Validation and Error States
HTML5 attributes such as required, type="email", and minlength="8" work well with JavaScript's Constraint Validation API. Use input.checkValidity() to test a field or the whole form, and input.setCustomValidity() to set your own error message. The attributes are covered in our HTML input attributes lesson.
Client-side checks improve the user experience only. Anyone can bypass them, so your backend must validate every input again.
const app = document.getElementById("app");
if (app) {
app.innerHTML = `
<form id="contact-form">
<input name="email" type="email" value="ada@example.com" required />
<input name="age" type="number" value="22" min="13" required />
<button type="submit">Join</button>
</form>
`;
const form = document.getElementById("contact-form");
const data = Object.fromEntries(new FormData(form));
const isValid = form.checkValidity();
console.log("Form valid:", isValid);
console.log("FormData payload:", data);
}This script builds a small form, reads its values, and checks validity. It logs Form valid: true and the payload object, because both pre-filled values satisfy their rules.
How to Check It Works
Add <div id="app"></div> to a page, include the script, and open the Console. You should see Form valid: true. Change the age value to 10 in the code and reload. The result should become false, because min="13" is no longer met. If FormData comes back empty, check that your inputs have name attributes.
Common JavaScript Form Mistakes
Listening for Button Click Instead of Form Submit
A click handler misses submissions made with the Enter key. Use form.addEventListener("submit", ...).
Forgetting name Attributes
FormData ignores any <input> or <select> without a name. If a field is missing from your payload, this is the first thing to check.
Reading Checkboxes with .value
A checkbox's .value is "on" by default, even when it is unchecked. Read checkbox. checked, which is a boolean. Note that FormData includes a checkbox only when it is checked.
Conclusion
Listen for submit, call preventDefault(), collect fields with FormData, and let the built-in validation catch obvious errors. Always validate again on the server. To send the collected data, continue with our Fetch API lesson. For a full reference, see MDN's guide to client-side form validation.
Frequently Asked Questions (FAQs)
What does event.preventDefault() do on a form submit event?
It stops the browser's traditional page-reloading submission, so your JavaScript can send a fetch() request and update the page smoothly.
How do I read values from a multi-select or checkbox group with FormData?
Call formData.getAll("fieldName"). It returns an array of every selected value for that name.
How can I reset all inputs in a form after saving?
Call form.reset(). It restores every input to its initial HTML default value.
Why does Object.fromEntries lose some checkbox values?
When several fields share one name, Object.fromEntries keeps only the last value. Use getAll() for groups.
Can I show my own error message?
Yes. Call input.setCustomValidity("Your message"), then form.reportValidity() to display it. Reset it with setCustomValidity("") once the input is fixed.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.