Skip to content

Forms and Validation

Forms are essential for collecting user input on web pages. Whether it’s a login form, a registration page, or a feedback form, handling forms effectively and validating input is critical for creating a seamless user experience. This guide will explore how to select form elements, read their values, prevent default behaviors, validate fields, display error messages, and submit forms using JavaScript.


To interact with forms and inputs using JavaScript, you first need to select the elements from the DOM. Common methods to select elements include:

If a form or input field has an id attribute, it can be quickly selected with getElementById:

const form = document.getElementById("userForm");
const usernameInput = document.getElementById("username");

You can also use CSS selectors to target form elements:

const form = document.querySelector("form");
const emailInput = document.querySelector("#email");

If you need to work with multiple input fields, use querySelectorAll or getElementsByTagName:

const inputs = document.querySelectorAll("input"); // NodeList of all input elements

Reading Values and Preventing Default Behavior

Section titled “Reading Values and Preventing Default Behavior”

Reading the values from form fields is straightforward using the .value property of input fields.

const username = document.querySelector("#username").value;
const email = document.querySelector("#email").value;
console.log(username, email);

HTML forms reload the page by default when submitted. To stop this default behavior, use event.preventDefault() in the form’s submit event listener:

const form = document.querySelector("form");
form.addEventListener("submit", (event) => {
event.preventDefault(); // Prevent the page reload
console.log("Form submission prevented");
});

Validation is crucial to ensure that users provide correct and complete information. Here’s how to handle client-side validation.

You can check if a value is empty or invalid using conditions:

form.addEventListener("submit", (event) => {
event.preventDefault();
const username = document.querySelector("#username").value;
const email = document.querySelector("#email").value;
if (!username) {
console.error("Username is required");
return;
}
if (!email.includes("@")) {
console.error("Invalid email address");
return;
}
console.log("Form is valid");
});

Instead of logging errors to the console, you can display error messages directly on the page:

const errorMessages = document.getElementById("errorMessages");
form.addEventListener("submit", (event) => {
event.preventDefault();
errorMessages.innerHTML = ""; // Clear previous messages
const username = document.querySelector("#username").value;
const email = document.querySelector("#email").value;
if (!username) {
errorMessages.innerHTML += "Username is required";
}
if (!email.includes("@")) {
errorMessages.innerHTML += "- Invalid email address";
}
});

Once validation is complete, you can submit the form programmatically or handle the data with JavaScript.

You can collect form data and send it to a server using fetch:

form.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries()); // Convert FormData to an object
fetch("[https://example.com/submit](https://example.com/submit)", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((result) => console.log("Form submitted successfully:", result))
.catch((error) => console.error("Error submitting form:", error));
});

After successful submission, you can reset the form’s input fields:

form.reset();