JavaScript Form Validation is a technique used to check and verify user input before sending form data to the server. It helps ensure that users enter correct, complete, and meaningful information.
Forms are an important part of websites. Login pages, registration systems, contact forms, payment pages, and online applications all require proper validation to prevent incorrect data submission.
JavaScript provides client-side validation methods that allow developers to immediately check user input and display helpful messages without waiting for server processing.
Form validation is the process of checking whether the information entered by a user follows specific rules or requirements.
For example, a registration form may require:
If the entered data is incorrect, JavaScript displays an error message and prevents form submission.
Without validation, users can submit incomplete or incorrect information, which may create problems for applications.
Form validation is mainly divided into two types:
| Type | Description |
|---|---|
| Client-Side Validation | Validation performed in the browser using JavaScript before data reaches the server. |
| Server-Side Validation | Validation performed on the server after receiving form data. |
Client-side validation happens directly inside the user's browser. JavaScript checks the input values and provides immediate responses.
Examples:
<form> Name: <input type="text" id="name"> Email: <input type="email" id="email"> <button type="submit"> Submit </button> </form>
JavaScript can access the values entered by users using the value property.
let username =
document.getElementById("name").value;
console.log(username);
One of the most common validation tasks is checking whether required fields contain data.
function validate()
{
let name =
document.getElementById("name").value;
if(name=="")
{
alert("Name is required");
return false;
}
}
JavaScript provides events that help perform validation when users interact with forms.
| Event | Description |
|---|---|
| submit | Runs when the form is submitted. |
| input | Runs whenever the user enters data. |
| change | Runs when the value of an element changes. |
| focus | Runs when an input field becomes active. |
| blur | Runs when an input field loses focus. |
The preventDefault() method stops the default form submission process.
form.addEventListener(
"submit",
function(event)
{
event.preventDefault();
});
This allows JavaScript to validate data before submitting the form.
Required field validation ensures that important fields are not left empty.
function checkName()
{
let name =
document.getElementById("name").value;
if(name.length == 0)
{
return false;
}
return true;
}
Email validation is used to check whether the email address entered by the user follows a correct format. A valid email usually contains a username, an @ symbol, and a domain name.
Email validation helps prevent users from entering incorrect email addresses in registration, login, and contact forms.
function validateEmail()
{
let email =
document.getElementById("email").value;
if(email=="")
{
alert("Email is required");
return false;
}
else
{
alert("Email Accepted");
return true;
}
}
Regular Expression (Regex) is a pattern used to search and verify specific formats of text.
function checkEmail()
{
let email =
document.getElementById("email").value;
let pattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if(pattern.test(email))
{
alert("Valid Email");
}
else
{
alert("Invalid Email");
}
}
Password validation ensures that users create secure passwords according to required rules.
A strong password generally contains:
function checkPassword()
{
let password =
document.getElementById("password").value;
if(password.length < 6)
{
alert("Password must contain minimum 6 characters");
return false;
}
return true;
}
function passwordStrength()
{
let password =
document.getElementById("password").value;
let pattern =
/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$/;
if(pattern.test(password))
{
alert("Strong Password");
}
else
{
alert("Weak Password");
}
}
Confirm password validation checks whether the password and confirm password fields contain the same value.
function checkConfirmPassword()
{
let password =
document.getElementById("password").value;
let confirm =
document.getElementById("confirm").value;
if(password != confirm)
{
alert("Password does not match");
return false;
}
return true;
}
Mobile number validation checks whether the entered phone number contains the correct number of digits.
function validateMobile()
{
let mobile =
document.getElementById("mobile").value;
let pattern =
/^[0-9]{10}$/;
if(pattern.test(mobile))
{
alert("Valid Mobile Number");
}
else
{
alert("Enter 10 digit mobile number");
}
}
JavaScript can check whether a user entered a valid numeric value.
let age =
document.getElementById("age").value;
if(isNaN(age))
{
alert("Please enter a number");
}
Good form validation should display clear messages near the incorrect input field instead of showing only alert boxes.
function validateName()
{
let name =
document.getElementById("name").value;
let error =
document.getElementById("error");
if(name=="")
{
error.innerHTML =
"Name cannot be empty";
}
else
{
error.innerHTML="";
}
}
Real-time validation checks user input while typing. It helps users correct mistakes immediately.
The input event is commonly used for real-time validation.
input.addEventListener(
"input",
function()
{
console.log(input.value);
});
Real-world forms usually require multiple validation rules together.
function validateForm()
{
let name =
document.getElementById("name").value;
let email =
document.getElementById("email").value;
let password =
document.getElementById("password").value;
if(name=="")
{
alert("Enter Name");
return false;
}
if(email=="")
{
alert("Enter Email");
return false;
}
if(password.length < 6)
{
alert("Password too short");
return false;
}
return true;
}
HTML5 provides built-in validation attributes that work together with JavaScript.
| Attribute | Purpose |
|---|---|
| required | Makes a field compulsory. |
| minlength | Sets minimum characters. |
| maxlength | Sets maximum characters. |
| pattern | Defines custom validation pattern. |
| min and max | Sets numeric limits. |
<input type="text" required>
The browser prevents submission when the field is empty.
<input
type="text"
pattern="[0-9]{10}"
>
This accepts only a 10-digit number.
function register()
{
let username =
document.getElementById("username").value;
let email =
document.getElementById("email").value;
let password =
document.getElementById("password").value;
if(username=="")
{
alert("Enter username");
return false;
}
if(email=="")
{
alert("Enter email");
return false;
}
if(password.length < 8)
{
alert("Password must contain 8 characters");
return false;
}
alert("Registration Successful");
}
A registration form is one of the most common examples where JavaScript validation is used. It checks user information before creating an account.
A good registration form validates username, email, password, confirm password, and mobile number fields.
<form onsubmit="return validateForm()">
<input type="text" id="username" placeholder="Enter Username">
<input type="email" id="email" placeholder="Enter Email">
<input type="password" id="password" placeholder="Enter Password">
<input type="password" id="confirmPassword" placeholder="Confirm Password">
<button type="submit">
Register
</button>
</form>
<script>
function validateForm()
{
let username =
document.getElementById("username").value;
let email =
document.getElementById("email").value;
let password =
document.getElementById("password").value;
let confirmPassword =
document.getElementById("confirmPassword").value;
if(username=="")
{
alert("Please enter username");
return false;
}
if(email=="")
{
alert("Please enter email");
return false;
}
if(password.length < 6)
{
alert("Password must contain minimum 6 characters");
return false;
}
if(password != confirmPassword)
{
alert("Password does not match");
return false;
}
alert("Registration Successful");
return true;
}
</script>
Login forms use validation to ensure that users provide required credentials before authentication.
function loginValidation()
{
let username =
document.getElementById("username").value;
let password =
document.getElementById("password").value;
if(username=="")
{
alert("Enter username");
return false;
}
if(password=="")
{
alert("Enter password");
return false;
}
alert("Login Successful");
}
Professional websites usually display validation messages near the related input field instead of using alert boxes.
<input id="email">
<span id="emailError"></span>
<script>
function checkEmail()
{
let email =
document.getElementById("email").value;
let error =
document.getElementById("emailError");
if(email=="")
{
error.innerHTML =
"Email is required";
}
else
{
error.innerHTML =
"";
}
}
</script>
JavaScript can modify CSS styles to highlight invalid fields.
let input =
document.getElementById("email");
input.style.border =
"2px solid red";
This technique improves user experience by visually showing incorrect fields.
input.style.border = "";
When the user enters correct information, the error style can be removed.
Many websites display password strength while users type passwords.
function checkPasswordStrength()
{
let password =
document.getElementById("password").value;
let result =
document.getElementById("strength");
if(password.length < 6)
{
result.innerHTML="Weak Password";
}
else if(password.length < 10)
{
result.innerHTML="Medium Password";
}
else
{
result.innerHTML="Strong Password";
}
}
Regular expressions allow developers to create custom validation rules for different types of data.
| Data | Pattern Example |
|---|---|
| Mobile Number | ^[0-9]{10}$ |
| Only Letters | ^[A-Za-z]+$ |
| Username | ^[A-Za-z0-9_]{5,}$ |
| ^[^\s@]+@[^\s@]+\.[^\s@]+$ |
function usernameCheck()
{
let username =
document.getElementById("username").value;
let pattern =
/^[A-Za-z0-9_]{5,}$/;
if(pattern.test(username))
{
alert("Valid Username");
}
else
{
alert("Invalid Username");
}
}
Sometimes developers need to clear form data after successful submission.
document
.getElementById("form")
.reset();
The reset() method clears all form fields.
The preventDefault() method allows developers to stop form submission until validation is completed.
form.addEventListener(
"submit",
function(event)
{
if(validationFailed)
{
event.preventDefault();
}
});
JavaScript form validation is used in almost every interactive website.
JavaScript Form Validation is an important technique used to verify user input before submitting data. It helps create secure, reliable, and user-friendly web applications.
Important concepts include checking empty fields, email validation, password verification, regular expressions, error handling, DOM manipulation, and form events.
A strong understanding of JavaScript form validation helps developers build professional websites with better user experience and accurate data handling.