HTML Form Validation Using JavaScript
Form validation ensures that users enter the correct data in a web form before submitting it.
Validation can be done on the client side using JavaScript or on the server side using backend
programming languages. Client-side validation improves user experience by providing
immediate feedback, reducing unnecessary server requests.
1. Integrating JavaScript with HTML Forms
JavaScript can be integrated into an HTML form using:
Inline event handlers (inside HTML attributes)
JavaScript functions (using onclick, onsubmit, etc.)
External JavaScript files (.js files linked with <script> tag)
Example of JavaScript Integration in an HTML Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<script src="validation.js"></script> <!-- External JavaScript File -->
</head>
<body>
<form name="myForm" onsubmit="return validateForm()" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
let name = document.forms["myForm"]["name"].value;
let email = document.forms["myForm"]["email"].value;
let password = document.forms["myForm"]["password"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (password.length < 6) {
alert("Password must be at least 6 characters long");
return false;
}
return true;
}
</script>
</body>
</html>
The onsubmit event in the <form> tag calls the validateForm() function.
The function retrieves input values and checks conditions.
If a validation rule fails, an alert is shown, and return false; prevents form submission.
---
2. Accessing HTML Elements Using JavaScript
JavaScript provides different ways to access form elements:
Methods to Access Elements
Example
let nameValue = document.getElementById("name").value;
let emailValue = document.forms["myForm"]["email"].value;
console.log(nameValue, emailValue);
---
3. Validating Different HTML Elements
Here’s how to validate different form inputs:
a) Text Field Validation
Ensure it's not empty.
Check for minimum and maximum length.
function validateTextField() {
let name = document.getElementById("name").value;
if (name.trim() === "") {
alert("Name is required.");
return false;
}
if (name.length < 3) {
alert("Name must be at least 3 characters.");
return false;
}
return true;
}
b) Email Validation
Check if the email follows the correct format using a regex pattern.
function validateEmail() {
let email = document.getElementById("email").value;
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
alert("Invalid email format.");
return false;
}
return true;
}
c) Password Validation
Ensure the password has at least 6 characters, includes numbers, and special characters.
function validatePassword() {
let password = document.getElementById("password").value;
let passwordPattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&*!]).{6,}$/;
if (!passwordPattern.test(password)) {
alert("Password must be at least 6 characters long and include uppercase, lowercase,
number, and special character.");
return false;
}
return true;
}
d) Checkbox Validation
function validateCheckbox() {
let checkbox = document.getElementById("terms");
if (!checkbox.checked) {
alert("You must agree to the terms and conditions.");
return false;
}
return true;
}
e) Radio Button Validation
function validateRadio() {
let gender = document.querySelector('input[name="gender"]:checked');
if (!gender) {
alert("Please select your gender.");
return false;
}
return true;
}
f) Dropdown (Select) Validation
function validateSelect() {
let country = document.getElementById("country").value;
if (country === "Select") {
alert("Please select a country.");
return false;
}
return true;
}
---
4. Full Practice Form Validation
Here's a complete form with multiple validations.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Form Validation</title>
</head>
<body>
<form name="registrationForm" onsubmit="return validateAll()">
<label for="name">Name:</label>
<input type="text" id="name"><br><br>
<label for="email">Email:</label>
<input type="text" id="email"><br><br>
<label for="password">Password:</label>
<input type="password" id="password"><br><br>
<label for="gender">Gender:</label>
<input type="radio" name="gender" value="Male"> Male
<input type="radio" name="gender" value="Female"> Female<br><br>
<label for="country">Country:</label>
<select id="country">
<option value="Select">Select</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select><br><br>
<input type="checkbox" id="terms"> I agree to the terms<br><br>
<input type="submit" value="Register">
</form>
<script>
function validateAll() {
return validateTextField() && validateEmail() && validatePassword() && validateRadio()
&& validateSelect() && validateCheckbox();
}
</script>
</body>
</html>
Key Features
Calls multiple validation functions.
Ensures all inputs meet criteria before form submission.
Prevents form submission if validation fails.
---
Conclusion
JavaScript allows real-time client-side form validation.
document.getElementById() and document.forms[] help access form fields.
Use regex for pattern-based validation (e.g., emails, passwords).
Combine multiple validation checks in a single function for better usabi