Form Validation
Build smarter, friendlier forms! Learn how to check required fields, validate email addresses, verify passwords, and guide visitors toward successful submissions.
const email =
document.getElementById(
"email"
);
if (email.validity.valid) {
console.log("Valid email!");
}
What Is Form Validation?
Forms appear everywhere: registration pages, contact forms, login screens, and online applications. Before accepting the information someone enters, a website should check whether it meets the expected requirements.
This process is called form validation. Validation can identify missing information, incorrectly formatted values, and entries that don’t match.
<form id="signupForm">
<label for="email">Email address</label>
<input id="email" type="email" required>
<button type="submit">Sign Up</button>
</form>The browser already understands some validation rules. Here, required means the field cannot be empty, and type="email" asks the browser to check for a basic email-address format.
Check That Visitors Enter Something
One of the most common validation tasks is ensuring that required information isn’t missing. JavaScript can read an input’s value and check whether it contains meaningful text.
const nameInput = document.getElementById("name");
const name = nameInput.value.trim();
if (name === "") {
console.log("Please enter your name.");
} else {
console.log("Hello, " + name + "!");
}The trim() method removes whitespace from both ends. Without it, someone could enter only spaces and pass a simple nonempty check.
HTML’s required attribute provides a useful first layer. JavaScript lets you customize the messages and handle more specific rules.
Check Email Address Formatting
An email field should contain an address in a recognizable format. The browser can perform a basic syntax check when an input uses type="email".
const email = document.getElementById("email");
if (email.validity.valueMissing) {
console.log("Email is required.");
} else if (email.validity.typeMismatch) {
console.log("Enter a valid email address.");
} else {
console.log("Email format accepted.");
}The validity property exposes several useful checks. valueMissing detects a missing required value, and typeMismatch identifies a value that doesn’t meet the input type’s basic formatting rules.
Validate Password Rules
Registration forms often require passwords to meet specific conditions. JavaScript can check those conditions and provide immediate feedback.
const password = document.getElementById("password").value;
if (password.length < 8) {
console.log("Use at least 8 characters.");
} else {
console.log("Minimum length met.");
}For this learning exercise, we’ll use a minimum of eight characters. Real applications should follow their own security requirements, encourage longer passwords, and support password managers.
To check that two password fields match, compare their values:
const password = document.getElementById("password").value;
const confirm = document.getElementById("confirm").value;
if (password !== confirm) {
console.log("Passwords do not match.");
}Guide Visitors Toward a Solution
Good validation should do more than say something is wrong. It should explain what needs to be corrected.
Instead of a generic “Invalid form” message, show specific feedback near the affected field.
const input = document.getElementById("username");
const error = document.getElementById("usernameError");
if (input.value.trim() === "") {
error.textContent = "Please enter a username.";
input.setAttribute("aria-invalid", "true");
} else {
error.textContent = "";
input.removeAttribute("aria-invalid");
}Using textContent ensures that the message is displayed as text. The aria-invalid attribute helps communicate invalid field states to assistive technologies.
Connect each error message to its input with aria-describedby so the relationship is accessible.
Prevent Invalid Form Submissions
Remember the submit event from Lesson 12? We can use it to check every field before proceeding.
const form = document.getElementById("signupForm");
form.addEventListener("submit", function(event) {
event.preventDefault();
const name = document.getElementById("name").value.trim();
if (!name) {
console.log("Please enter your name.");
return;
}
console.log("Demo form passed validation!");
});preventDefault() keeps this demonstration on the same page. In a real application, successfully validated data would then be submitted through an appropriate, secure process.
You can also call checkValidity() to ask whether an HTML form meets its built-in validation constraints.
if (form.checkValidity()) {
console.log("Browser validation passed.");
} else {
console.log("Please correct the form.");
}Try a Live Registration Form
Let’s bring everything together. Enter a name, email, and password below. The demonstration checks the fields and displays a success message only when they meet the example requirements.
Try submitting the form empty, entering an invalid email, using a short password, or entering two different passwords. Then correct the values and submit again.
Build a Smart Registration Form
Create a registration form that checks user input and guides visitors through correcting mistakes.
Your Mission
- Create fields for full name, email, password, and password confirmation.
- Make sure the name and email are not empty.
- Use
type="email"and the browser’s validity API to check email formatting. - Require a password containing at least eight characters.
- Check that the password and confirmation match.
- Display specific error messages next to invalid fields.
- Prevent submission and display a success message when every rule passes.
Build Your Smart Registration Form!
Edit the starter code and test your validation rules. The Load Solution button adds live field feedback, a password-strength indicator, confirmation matching, and a terms checkbox.
What You’ve Learned
You’re Building Smarter Forms!
You now know how to check input, prevent invalid submissions, and guide visitors with clear validation messages.
- Understand why form validation matters.
- Check required fields using
trim(). - Use HTML email validation and the
validityAPI. - Validate password length and confirmation fields.
- Display accessible, field-specific error messages.
- Handle form submissions with
preventDefault(). - Build a Smart Registration Form with JavaScript.
Next up: JSON — learn how JavaScript applications organize and exchange structured information!
Your Learning Journey
0 / 17 CompletedLesson 13 of 17 — you’re getting closer to the final project!
You've Mastered Form Validation Basics!
You can now check required fields, validate email formats, compare passwords, and display helpful error messages. You've also built your own Smart Registration Form!


