Build a JavaScript Form Validation
In this project, you will learn how to validate form inputs using JavaScript before allowing the form to be submitted.
Project Introduction
Form validation checks whether the information entered by a user is valid and complete.
What You Will Learn
- HTML forms
- Input values
- Required field validation
- Email validation
- Password validation
- Number validation
- Regular expressions
- DOM manipulation
- preventDefault()
Create the HTML Form
Start with a simple registration form containing name, email, password and age fields.
<form id="registrationForm">
<input
type="text"
id="name"
placeholder="Full Name"
>
<input
type="email"
id="email"
placeholder="Email"
>
<input
type="password"
id="password"
placeholder="Password"
>
<input
type="number"
id="age"
placeholder="Age"
>
<button type="submit">
Register
</button>
</form>
Add Error Message Elements
Create separate elements where validation errors can be displayed.
<span id="nameError"></span> <span id="emailError"></span> <span id="passwordError"></span> <span id="ageError"></span>
JavaScript can update these elements whenever an input contains an error.
Get Form Values
Use getElementById() and the value property to read the information entered by the user.
const name =
document.getElementById("name").value;
const email =
document.getElementById("email").value;
const password =
document.getElementById("password").value;
const age =
document.getElementById("age").value;
Validate Required Fields
The simplest validation is checking whether an input is empty.
if(name.trim() === ""){
nameError.textContent =
"Name is required.";
}
Why trim()?
trim() removes extra spaces from the beginning and end of a string.
const cleanName =
name.trim();
Validate Email
A regular expression can be used to check whether an email has a basic valid structure.
const emailPattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if(!emailPattern.test(email)){
emailError.textContent =
"Please enter a valid email.";
}
Validate Password
A basic registration form can require a minimum password length.
if(password.length < 8){
passwordError.textContent =
"Password must contain at least 8 characters.";
}
Stronger Password Check
const strongPassword =
/^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
if(!strongPassword.test(password)){
passwordError.textContent =
"Use at least 8 characters with letters and numbers.";
}
Validate Number
Convert the age value into a number and check whether it falls inside the required range.
const ageNumber =
Number(age);
if(
!ageNumber ||
ageNumber < 18 ||
ageNumber > 100
){
ageError.textContent =
"Enter an age between 18 and 100.";
}
Create Custom Validation
You can combine multiple validation rules to create a complete validation function.
function validateName(){
const value =
nameInput.value.trim();
if(value === ""){
return "Name is required.";
}
if(value.length < 3){
return "Name must contain at least 3 characters.";
}
return "";
}
Prevent Form Submission
The form normally submits when the user clicks the submit button. JavaScript can stop this behavior while validation is being performed.
form.addEventListener(
"submit",
function(event){
event.preventDefault();
}
);
Why preventDefault()?
It prevents the browser's default form submission behavior, allowing JavaScript to validate the data first.
Display Error Messages
Error messages should clearly explain what the user needs to correct.
function showError(
element,
message
){
element.textContent =
message;
}
Clear Errors
function clearErrors(){
nameError.textContent = "";
emailError.textContent = "";
passwordError.textContent = "";
ageError.textContent = "";
}
Complete Project Flow
Complete Form Validation Project
You have now learned how to read form values, validate required fields, check email structure, validate passwords, check numbers, show errors and control form submission.
Tutorial Completed! 📝
Now open the complete working Form Validation project and test the validation rules.
Run Complete Project Learn JavaScript Forms