Best Practices
Client-Side validation with JavaScript
1. Required Field
Validation (Beginner)
Problem:
Create a form with
"Name" and "Email" fields. Ensure that both fields are not
left empty when the form is submitted.
Solution:
<form id="basicForm">
Name: <input type="text" id="name"><br>
Email: <input type="email" id="email"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("basicForm").onsubmit
= function(event) {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if (!name || !email) {
alert("Both fields are
required.");
event.preventDefault();
}
};
</script>
Explanation: This
validation checks if the "Name" and "Email" fields are
empty. If either field is empty, an alert is shown, and the form submission is
prevented.
2. Email Format
Validation (Beginner)
Problem:
Create a form with an
email input field. Validate if the email is in the correct format (e.g.,
user@example.com).
Solution:
<form id="emailForm">
Email: <input type="email" id="email"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("emailForm").onsubmit
= function(event) {
var email = document.getElementById("email").value;
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!email.match(emailPattern)) {
alert("Please enter a valid email
address.");
event.preventDefault();
}
};
</script>
Explanation: This
validates the email format using a regular expression that checks if the email
contains letters, numbers, and special characters before the @ symbol and a
domain after it.
3. Password Length
Validation (Beginner)
Problem:
Create a form with a
password input field. Validate that the password is at least 8 characters long.
Solution:
<form id="passwordForm">
Password: <input type="password"
id="password"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("passwordForm").onsubmit
= function(event) {
var password = document.getElementById("password").value;
if (password.length < 8) {
alert("Password must be at least 8
characters long.");
event.preventDefault();
}
};
</script>
Explanation:
This checks if the password length is less than 8 characters. If true, it
prevents form submission and displays an alert.
4. Confirm Password
Validation (Beginner)
Problem:
Create a form with
"Password" and "Confirm Password" fields. Ensure that both
passwords match.
Solution:
<form id="passwordForm">
Password: <input type="password"
id="password"><br>
Confirm Password: <input type="password"
id="confirmPassword"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("passwordForm").onsubmit
= function(event) {
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmPassword").value;
if (password !== confirmPassword) {
alert("Passwords do not
match.");
event.preventDefault();
}
};
</script>
Explanation:
This ensures that the password and the confirm password fields have the same
value. If they don't match, the form submission is prevented.
5. Phone Number
Validation (Beginner)
Problem:
Create a form with a
phone number input field. Validate that the phone number follows the format (XXX)
XXX-XXXX.
Solution:
<form id="phoneForm">
Phone Number: <input type="text"
id="phone"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("phoneForm").onsubmit
= function(event) {
var phone = document.getElementById("phone").value;
var phonePattern = /^\(\d{3}\)
\d{3}-\d{4}$/;
if (!phone.match(phonePattern)) {
alert("Please enter a valid phone
number in the format (XXX) XXX-XXXX.");
event.preventDefault();
}
};
</script>
Explanation:
This checks if the phone number matches the required format using a regular
expression.
6. Date Validation
(Beginner)
Problem:
Create a form with a date
input field. Ensure that the entered date is not in the future.
Solution:
<form id="dobForm">
Date of Birth: <input type="date"
id="dob"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("dobForm").onsubmit
= function(event) {
var dob = new Date(document.getElementById("dob").value);
var today = new Date();
if (dob > today) {
alert("Date of birth cannot be in
the future.");
event.preventDefault();
}
};
</script>
Explanation:
This compares the selected date with today's date. If the date of birth is in
the future, the form submission is prevented.
7. Checkbox Validation
(Intermediate)
Problem:
Create a form with a
checkbox for agreeing to the terms and conditions. Ensure that the checkbox is
checked before submitting.
Solution:
<form id="termsForm">
<label for="terms">I agree
to the terms and conditions</label>
<input type="checkbox" id="terms"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("termsForm").onsubmit
= function(event) {
var terms = document.getElementById("terms").checked;
if (!terms) {
alert("You must agree to the terms
and conditions.");
event.preventDefault();
}
};
</script>
Explanation: This
validates if the checkbox is checked before submitting the form. If not, it
displays an alert and prevents the submission.
8. Multiple Field
Validation (Intermediate)
Problem:
Create a form with
"Username" and "Password". Ensure that both fields are
filled, and the username is at least 5 characters long.
Solution:
<form id="multipleFieldsForm">
Username: <input type="text" id="username"><br>
Password: <input type="password"
id="password"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("multipleFieldsForm").onsubmit
= function(event) {
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (!username || username.length < 5) {
alert("Username must be at least 5
characters.");
event.preventDefault();
}
if (!password) {
alert("Password cannot be
empty.");
event.preventDefault();
}
};
</script>
Explanation:
This ensures that the username is at least 5 characters and the password is not
empty.
9. Select Box Validation
(Intermediate)
Problem:
Create a form with a
select box for choosing a country. Ensure that the user selects a country.
Solution:
<form id="selectBoxForm">
Select your country:
<select id="country">
<option value="">Select
a country</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="India">India</option>
</select><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("selectBoxForm").onsubmit
= function(event) {
var country = document.getElementById("country").value;
if (!country) {
alert("Please select a
country.");
event.preventDefault();
}
};
</script>
Explanation: This
checks whether a valid country is selected from the dropdown. If not, the form
submission is prevented.
10. Numeric Input
Validation (Intermediate)
Problem:
Create a form with an
"Age" field that accepts only numeric values between 18 and 100.
Solution:
<form id="numericForm">
Age: <input type="number" id="age"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("numericForm").onsubmit
= function(event) {
var age = document.getElementById("age").value;
if (age < 18 || age > 100) {
alert("Age must be between 18 and
100.");
event.preventDefault();
}
};
</script>
Explanation: This
ensures that the age is between 18 and 100. If it's not, the form submission is
prevented.
11. Range Validation
(Intermediate)
Problem:
Create a form with a
"Salary" field that only accepts values between 1000 and 10000.
Solution:
<form id="rangeForm">
Salary: <input type="number" id="salary"
min="1000" max="10000"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("rangeForm").onsubmit
= function(event) {
var
salary = document.getElementById("salary").value;
if (salary < 1000 || salary > 10000) {
alert("Salary must be between 1000
and 10000.");
event.preventDefault();
}
};
</script>
Explanation: This
ensures that the salary value is within the specified range of 1000 and 10000.
12. Regular Expression
(Advanced)
Problem:
Create a form where the
username must start with a letter and can contain only letters, numbers, and
underscores.
Solution:
<form id="regexForm">
Username: <input type="text" id="username"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("regexForm").onsubmit
= function(event) {
var username = document.getElementById("username").value;
var usernamePattern = /^[A-Za-z][A-Za-z0-9_]*$/;
if (!username.match(usernamePattern)) {
alert("Username must start with a
letter and can contain only letters, numbers, and underscores.");
event.preventDefault();
}
};
</script>
Explanation: This
regular expression checks that the username starts with a letter and contains
only letters, numbers, and underscores.
13. Zip Code Validation
(Advanced)
Problem:
Create a form with a
"Zip Code" field that accepts only 5-digit zip codes.
Solution:
<form id="zipForm">
Zip Code: <input type="text" id="zipCode"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("zipForm").onsubmit
= function(event) {
var zipCode = document.getElementById("zipCode").value;
var zipCodePattern = /^\d{5}$/;
if (!zipCode.match(zipCodePattern)) {
alert("Zip code must be 5
digits.");
event.preventDefault();
}
};
</script>
Explanation:
This regular expression ensures that the zip code entered contains exactly 5
digits.
14. Form Reset
Confirmation (Advanced)
Problem:
Create a form and ask for
confirmation before resetting the form.
Solution:
<form id="resetForm">
Name: <input type="text" id="name"><br>
<input type="reset" value="Reset"
onclick="return confirm('Are you sure you want to reset the form?');">
<input type="submit" value="Submit">
</form>
Explanation:
This solution confirms with the user before allowing the form to be reset.
15. Time Validation
(Advanced)
Problem:
Create a form with a
"Time" field. Ensure that the time is between 9:00 AM and 5:00 PM.
Solution:
<form id="timeForm">
Work Time: <input type="time" id="workTime"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("timeForm").onsubmit
= function(event) {
var workTime = document.getElementById("workTime").value;
var timePattern = /^(0[9]|1[0-7]):([0-5][0-9])$/;
if (!workTime.match(timePattern)) {
alert("Please enter a time between
9:00 AM and 5:00 PM.");
event.preventDefault();
}
};
</script>
Explanation:
This regular expression checks if the entered time is between 9:00 AM and 5:00
PM.
16. Custom Error Message
(Advanced)
Problem:
Create a form that
validates the phone number and shows a custom error message.
Solution:
<form id="customMessageForm">
Phone Number: <input type="text"
id="phoneNumber"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("customMessageForm").onsubmit
= function(event) {
var phoneNumber = document.getElementById("phoneNumber").value;
var phonePattern = /^\d{10}$/;
if (!phoneNumber.match(phonePattern)) {
alert("Error: Phone number must be
exactly 10 digits.");
event.preventDefault();
}
};
</script>
Explanation: This
checks that the phone number is exactly 10 digits long and provides a custom
error message.
17. Password Strength
Validation (Advanced)
Problem:
Create a password field
that checks for strength. It should contain at least one uppercase letter, one
lowercase letter, one number, and one special character.
Solution:
<form id="passwordStrengthForm">
Password: <input type="password"
id="password"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("passwordStrengthForm").onsubmit
= function(event) {
var password = document.getElementById("password").value;
var passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
if (!password.match(passwordPattern)) {
alert("Password must contain at
least one uppercase letter, one lowercase letter, one number, and one special
character.");
event.preventDefault();
}
};
</script>
Explanation:
This regular expression ensures that the password meets the specified strength
requirements.
18. File Upload
Validation (Advanced)
Problem:
Create a form that only
accepts images (JPG, PNG, GIF) for file uploads.
Solution:
<form id="fileUploadForm">
Upload Image: <input type="file"
id="file"><br>
<input type="submit" value="Upload">
</form>
<script>
document.getElementById("fileUploadForm").onsubmit
= function(event) {
var file = document.getElementById("file").files[0];
var fileType = file.type;
if (!fileType.match('image/jpeg') && !fileType.match('image/png') && !fileType.match('image/gif')) {
alert("Only JPG, PNG, and GIF
images are allowed.");
event.preventDefault();
}
};
</script>
Explanation: This
checks the file type before submission and ensures that only image files are
uploaded.
19. Password Complexity
(Advanced)
Problem:
Create a form where the
password must contain at least one uppercase letter, one special character, and
be at least 8 characters long.
Solution:
<form id="passwordComplexityForm">
Password: <input type="password"
id="password"><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("passwordComplexityForm").onsubmit
= function(event) {
var password = document.getElementById("password").value;
var passwordPattern = /^(?=.*[A-Z])(?=.*[!@#$%^&*])[A-Za-z\d@$!%*?&]{8,}$/;
if (!password.match(passwordPattern)) {
alert("Password must contain at
least one uppercase letter, one special character, and be at least 8 characters
long.");
event.preventDefault();
}
};
</script>
Explanation:
This regular expression checks for the required password complexity.
20. Prevent Duplicates
(Advanced)
Problem:
Create a form with a
"Username" field. Ensure that the username does not already exist in
the system (simulated via an array).
Solution:
<form id="duplicateForm">
Username: <input type="text" id="username"><br>
<input type="submit" value="Submit">
</form>
<script>
var existingUsernames = ["user1",
"admin", "guest"];
document.getElementById("duplicateForm").onsubmit = function(event) {
var username = document.getElementById("username").value;
if (existingUsernames.includes(username)) {
alert("Username already exists.
Please choose another.");
event.preventDefault();
}
};
</script>
Explanation:
This checks if the entered username already exists in a predefined array and
prevents form submission if it's a duplicate.