Forms & Form Validation in JavaScript
Over the past few days, I've learned how JavaScript interacts with the DOM and responds to user events.
Today, I explored Forms and Form Validation.
Forms are one of the primary ways users provide information to a website.
JavaScript allows us to capture that information, validate it, prevent invalid submissions, and provide useful feedback to users.
Let's dive in.
What is an HTML Form?
An HTML <form> element is used to collect user input.
Example:
<form id="signupForm">
<input
type="text"
id="username"
placeholder="Enter your username"
>
<input
type="email"
id="email"
placeholder="Enter your email"
>
<button type="submit">
Sign Up
</button>
</form>
The form contains input fields and a submit button.
Selecting Form Elements
We can use the DOM to select the form and its inputs.
const form = document.querySelector("#signupForm");
const username = document.querySelector("#username");
const email = document.querySelector("#email");
Now JavaScript can interact with these elements.
Handling Form Submission
The submit event runs when the form is submitted.
form.addEventListener("submit", function (event) {
console.log("Form submitted!");
});
But there's an important problem.
By default, the browser may reload the page or navigate when a form is submitted.
preventDefault()
We can prevent the browser's default behavior using:
event.preventDefault();
Example:
form.addEventListener("submit", function (event) {
event.preventDefault();
console.log("Form submitted without reloading!");
});
This gives JavaScript control over what happens after submission.
Getting Input Values
The .value property allows us to access what the user entered.
console.log(username.value);
console.log(email.value);
For example, if the user enters:
Saurabh
Then:
username.value
returns:
Saurabh
Basic Form Validation
Validation means checking whether the user's input meets our requirements.
For example:
form.addEventListener("submit", function (event) {
event.preventDefault();
if (username.value === "") {
console.log("Username is required.");
}
});
Now the form checks whether the username field is empty.
Checking Multiple Fields
We can validate multiple inputs.
form.addEventListener("submit", function (event) {
event.preventDefault();
if (username.value === "") {
console.log("Username is required.");
}
if (email.value === "") {
console.log("Email is required.");
}
});
This allows us to provide specific feedback for each field.
Trimming User Input
Users may accidentally enter spaces before or after their input.
We can remove unnecessary whitespace using .trim().
const name = username.value.trim();
console.log(name);
For example:
" Saurabh "
becomes:
"Saurabh"
This is useful when validating text input.
Checking Email Format
JavaScript can use regular expressions to perform more advanced validation.
A simple example:
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email.value)) {
console.log("Enter a valid email.");
}
The test() method checks whether the value matches the pattern.
Client-side validation improves the user experience, but important validation should also be performed on the server because client-side checks can be bypassed.
Showing Error Messages
Instead of only printing errors in the console, we can show them on the webpage.
HTML:
<p id="error"></p>
JavaScript:
const error = document.querySelector("#error");
if (username.value.trim() === "") {
error.textContent = "Username is required.";
}
Now the user can actually see the error.
Checking Password Length
We can also validate password requirements.
const password = document.querySelector("#password");
if (password.value.length < 8) {
console.log("Password must contain at least 8 characters.");
}
This is a simple example of validation logic.
HTML Form Validation
HTML itself also provides built-in validation attributes.
For example:
<input
type="email"
required
>
Other useful attributes include:
requiredminlengthmaxlengthminmaxpatterntype
Example:
<input
type="text"
required
minlength="3"
maxlength="20"
>
HTML validation can handle many basic requirements before JavaScript even runs.
FormData
JavaScript also provides the FormData API for collecting form values.
Example:
form.addEventListener("submit", function (event) {
event.preventDefault();
const data = new FormData(form);
console.log(data.get("username"));
});
For this to work, the input needs a name attribute:
<input
type="text"
name="username"
>
FormData becomes especially useful when sending form information to a server.
Client-Side vs Server-Side Validation
This distinction is important.
Client-Side Validation
Runs in the browser.
Useful for:
Immediate feedback
Better user experience
Preventing obvious mistakes
Server-Side Validation
Runs on the backend.
Essential for:
Security
Data integrity
Protecting application logic
Client-side validation should never be treated as the only security layer.
Best Practices
✔ Always validate important user input.
✔ Use HTML's built-in validation when appropriate.
✔ Use JavaScript for custom validation and user feedback.
✔ Use .trim() when handling text input.
✔ Use event.preventDefault() when handling submission through JavaScript.
✔ Never rely only on client-side validation for security.
✔ Give users clear and specific error messages.
My Biggest Takeaway
Today, I learned how JavaScript can handle one of the most important interactions between a user and a website—form input.
I learned how to capture form submissions, access input values, prevent default browser behavior, validate user input, and display useful feedback.
I also learned an important real-world concept: client-side validation improves the user experience, but server-side validation is essential for security and data integrity.
Forms combine many of the concepts I've learned so far—DOM manipulation, events, conditions, strings, and functions.
