Introductions
Form validation checks whether the information entered by a user is correct before it is accepted or submitted. JavaScript can validate names, email addresses, passwords, numbers, required fields, and more. In this chapter, you will practice form validation from simple checks to a complete registration form. JavaScript Form Validation practice questions with solutions help to build concepts.
Question 1: Check Whether an Input Is Empty
Problem
Create a name input and check whether the user has entered a name before submitting the form.
Solution
<form id="nameForm">
<input
type="text"
id="name"
placeholder="Enter your name"
>
<button type="submit">Submit</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("nameForm");
const name = document.getElementById("name");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
if (name.value.trim() === "") {
message.textContent = "Please enter your name.";
} else {
message.textContent = "Form submitted successfully!";
}
});
</script>
Output
If the input is empty:
Please enter your name.
If the user enters:
Rahul
The output becomes:
Form submitted successfully!
Step-by-step Explanation
- JavaScript selects the form and input.
- The
submitevent runs when the form is submitted. preventDefault()stops the page from refreshing.trim()removes unnecessary spaces.- The
ifstatement checks whether the input is empty. - An error message is shown if no name is entered.
Question 2: Validate Minimum Name Length
Problem
Accept a name only if it contains at least 3 characters.
Solution
<form id="nameForm">
<input
type="text"
id="name"
placeholder="Enter your name"
>
<button type="submit">Submit</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("nameForm");
const name = document.getElementById("name");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
const nameValue = name.value.trim();
if (nameValue === "") {
message.textContent = "Name is required.";
} else if (nameValue.length < 3) {
message.textContent = "Name must contain at least 3 characters.";
} else {
message.textContent = "Valid name!";
}
});
</script>
Output
Input:
Al
Output:
Name must contain at least 3 characters.
Input:
Aman
Output:
Valid name!
Step-by-step Explanation
- Get the value from the input.
- Remove unnecessary spaces with
trim(). - Check whether the input is empty.
- Use
.lengthto count characters. - Reject names shorter than 3 characters.
- Accept names containing 3 or more characters.
Question 3: Validate an Email Address
Problem
Create an email field and check whether the entered email has a basic valid format.
Solution
<form id="emailForm">
<input
type="text"
id="email"
placeholder="Enter your email"
>
<button type="submit">Check Email</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("emailForm");
const email = document.getElementById("email");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
const emailValue = email.value.trim();
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailValue === "") {
message.textContent = "Email is required.";
} else if (!emailPattern.test(emailValue)) {
message.textContent = "Please enter a valid email.";
} else {
message.textContent = "Valid email address!";
}
});
</script>
Output
Input:
hello
Output:
Please enter a valid email.
Input:
student@example.com
Output:
Valid email address!
Step-by-step Explanation
- The email value is stored in
emailValue. emailPatterncontains a regular expression..test()checks whether the email matches the pattern.- An invalid email displays an error.
- A matching email is accepted.
Question 4: Validate Password Length
Problem
Create a password field. The password must contain at least 8 characters.
Solution
<form id="passwordForm">
<input
type="password"
id="password"
placeholder="Enter password"
>
<button type="submit">Check Password</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("passwordForm");
const password = document.getElementById("password");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
const passwordValue = password.value;
if (passwordValue === "") {
message.textContent = "Password is required.";
} else if (passwordValue.length < 8) {
message.textContent =
"Password must contain at least 8 characters.";
} else {
message.textContent = "Password is valid!";
}
});
</script>
Output
Input:
hello
Output:
Password must contain at least 8 characters.
Input:
javascript123
Output:
Password is valid!
Step-by-step Explanation
- Get the password value.
- Check whether it is empty.
- Use
.lengthto count characters. - Require at least 8 characters.
- Display an appropriate message.
Question 5: Confirm Two Passwords
Problem
Create password and confirm-password fields. Check whether both passwords are the same.
Solution
<form id="passwordForm">
<input
type="password"
id="password"
placeholder="Enter password"
>
<br><br>
<input
type="password"
id="confirmPassword"
placeholder="Confirm password"
>
<br><br>
<button type="submit">Register</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("passwordForm");
const password = document.getElementById("password");
const confirmPassword =
document.getElementById("confirmPassword");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
if (password.value === "") {
message.textContent = "Password is required.";
} else if (password.value !== confirmPassword.value) {
message.textContent = "Passwords do not match.";
} else {
message.textContent = "Passwords match!";
}
});
</script>
Output
If the passwords are:
Password: hello123
Confirm: hello456
Output:
Passwords do not match.
If both are:
hello123
Output:
Passwords match!
Step-by-step Explanation
- Get both password values.
- Check whether the password is empty.
- Compare both values using
!==. - If they are different, show an error.
- If they are the same, accept the passwords.
Question 6: Validate Age
Problem
Create an age input. Accept the form only when the user enters an age between 18 and 60.
Solution
<form id="ageForm">
<input
type="number"
id="age"
placeholder="Enter your age"
>
<button type="submit">Check Age</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("ageForm");
const age = document.getElementById("age");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
const ageValue = Number(age.value);
if (age.value === "") {
message.textContent = "Age is required.";
} else if (ageValue < 18 || ageValue > 60) {
message.textContent = "Age must be between 18 and 60.";
} else {
message.textContent = "Valid age!";
}
});
</script>
Output
Input:
15
Output:
Age must be between 18 and 60.
Input:
25
Output:
Valid age!
Step-by-step Explanation
- Get the value from the age field.
- Convert it into a number using
Number(). - Check whether the field is empty.
- Check whether the age is below 18 or above 60.
- Accept values from 18 through 60.
Question 7: Validate a Phone Number
Problem
Create a phone number field and check whether it contains exactly 10 digits.
Solution
<form id="phoneForm">
<input
type="text"
id="phone"
placeholder="Enter 10-digit phone number"
>
<button type="submit">Check Number</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("phoneForm");
const phone = document.getElementById("phone");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
const phoneValue = phone.value.trim();
const phonePattern = /^\d{10}$/;
if (phoneValue === "") {
message.textContent = "Phone number is required.";
} else if (!phonePattern.test(phoneValue)) {
message.textContent =
"Please enter exactly 10 digits.";
} else {
message.textContent = "Valid phone number!";
}
});
</script>
Output
Input:
98765
Output:
Please enter exactly 10 digits.
Input:
9876543210
Output:
Valid phone number!
Step-by-step Explanation
- Get the phone number.
^\d{10}$checks for exactly 10 digits..test()checks whether the value matches the pattern.- Invalid numbers are rejected.
- A 10-digit number is accepted.
Question 8: Validate a Required Select Box
Problem
Create a course dropdown. Display an error if the user does not select a course.
Solution
<form id="courseForm">
<select id="course">
<option value="">Select a course</option>
<option value="HTML">HTML</option>
<option value="CSS">CSS</option>
<option value="JavaScript">JavaScript</option>
</select>
<button type="submit">Submit</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("courseForm");
const course = document.getElementById("course");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
if (course.value === "") {
message.textContent = "Please select a course.";
} else {
message.textContent =
"Selected course: " + course.value;
}
});
</script>
Output
Without selecting a course:
Please select a course.
After selecting JavaScript:
Selected course: JavaScript
Step-by-step Explanation
- The first option has an empty value.
- JavaScript reads
course.value. - If the value is empty, an error is displayed.
- Otherwise, the selected course is accepted.
Question 9: Validate a Checkbox
Problem
Create a terms-and-conditions checkbox. The user must check it before submitting.
Solution
<form id="termsForm">
<label>
<input type="checkbox" id="terms">
I agree to the terms and conditions
</label>
<br><br>
<button type="submit">Continue</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("termsForm");
const terms = document.getElementById("terms");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
if (!terms.checked) {
message.textContent =
"Please accept the terms and conditions.";
} else {
message.textContent =
"Terms accepted. You can continue.";
}
});
</script>
Output
If the checkbox is not selected:
Please accept the terms and conditions.
If the checkbox is selected:
Terms accepted. You can continue.
Step-by-step Explanation
- JavaScript selects the checkbox.
.checkedtells us whether the checkbox is selected.!terms.checkedmeans the checkbox is not selected.- An error is displayed when it is unchecked.
- The form is accepted when it is checked.
Question 10: Build a Complete Registration Form Validation
Problem
Create a registration form with:
- Name
- Password
- Confirm password
- Age
- Terms checkbox
Validate all fields before displaying a success message.
Solution
<form id="registrationForm">
<input
type="text"
id="name"
placeholder="Enter your name"
>
<br><br>
<input
type="email"
id="email"
placeholder="Enter your email"
>
<br><br>
<input
type="password"
id="password"
placeholder="Enter password"
>
<br><br>
<input
type="password"
id="confirmPassword"
placeholder="Confirm password"
>
<br><br>
<input
type="number"
id="age"
placeholder="Enter your age"
>
<br><br>
<label>
<input type="checkbox" id="terms">
I agree to the terms
</label>
<br><br>
<button type="submit">Register</button>
</form>
<p id="message"></p>
<script>
const form = document.getElementById("registrationForm");
const name = document.getElementById("name");
const email = document.getElementById("email");
const password = document.getElementById("password");
const confirmPassword =
document.getElementById("confirmPassword");
const age = document.getElementById("age");
const terms = document.getElementById("terms");
const message = document.getElementById("message");
form.addEventListener("submit", function(event) {
event.preventDefault();
const nameValue = name.value.trim();
const emailValue = email.value.trim();
const ageValue = Number(age.value);
const emailPattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (nameValue === "") {
message.textContent = "Name is required.";
} else if (nameValue.length < 3) {
message.textContent =
"Name must contain at least 3 characters.";
} else if (!emailPattern.test(emailValue)) {
message.textContent =
"Please enter a valid email.";
} else if (password.value.length < 8) {
message.textContent =
"Password must contain at least 8 characters.";
} else if (password.value !== confirmPassword.value) {
message.textContent =
"Passwords do not match.";
} else if (age.value === "" || ageValue < 18) {
message.textContent =
"You must be at least 18 years old.";
} else if (!terms.checked) {
message.textContent =
"Please accept the terms.";
} else {
message.textContent =
"Registration successful!";
}
});
</script>
Output
If the form contains invalid information:
Please enter a valid email.
or:
Password must contain at least 8 characters.
or:
Passwords do not match.
When all conditions are satisfied:
Registration successful!
Step-by-step Explanation
- JavaScript selects the complete form.
- It selects every input that needs validation.
preventDefault()stops the default form submission.- The name is checked first.
- The name length is checked.
- The email is tested using a regular expression.
- The password length is checked.
- The two passwords are compared.
- The age is converted to a number and checked.
- The checkbox is checked using
.checked. - If any validation fails, an error message is displayed.
- If all checks pass, the success message is displayed.
Key Takeaways
- Form validation checks user input before accepting it.
submitis commonly used for form validation.event.preventDefault()prevents normal form submission.valuegets the user’s input.trim()removes unnecessary spaces.lengthchecks the number of characters.Number()converts text into a number.- Regular expressions can validate patterns such as email and phone numbers.
.checkedchecks whether a checkbox is selected.if,else if, andelseare commonly used for validation rules.- Client-side validation improves user experience.
- Real applications should also validate data on the server because JavaScript validation alone should not be treated as a security measure.
FAQs
1. What is form validation in JavaScript?
Form validation means checking user input before allowing the form to be submitted or processed.
For example:
if (name.value.trim() === "") {
message.textContent = "Name is required.";
}
2. Why do we use event.preventDefault() in form validation?
It prevents the browser from performing its normal form submission.
form.addEventListener("submit", function(event) {
event.preventDefault();
});
This allows JavaScript to validate the data first.
3. How can I check whether an input is empty?
Use value and trim():
if (input.value.trim() === "") {
console.log("Input is empty");
}
4. How can I check the minimum password length?
Use the length property:
if (password.value.length < 8) {
console.log("Password is too short");
}
5. How can I check whether two passwords match?
Compare their values:
if (password.value !== confirmPassword.value) {
console.log("Passwords do not match");
}
6. How do I check whether a checkbox is selected?
Use the .checked property:
if (!terms.checked) {
console.log("Please accept the terms.");
}
7. Is JavaScript form validation enough for website security?
No. JavaScript validation happens in the user’s browser and can be bypassed. Important data should also be validated and secured on the server.
Client-side validation is mainly useful for providing quick feedback and improving the user experience.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
