CS Engineering Gyan

JavaScript Form Validation

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.


What is Form Validation?

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.


Why is Form Validation Important?

Without validation, users can submit incomplete or incorrect information, which may create problems for applications.

Advantages of JavaScript Form Validation


Types of Form Validation

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 Using JavaScript

Client-side validation happens directly inside the user's browser. JavaScript checks the input values and provides immediate responses.

Examples:


Basic HTML Form Example


<form>


Name:

<input type="text" id="name">


Email:

<input type="email" id="email">


<button type="submit">

Submit

</button>


</form>


Accessing Form Values Using JavaScript

JavaScript can access the values entered by users using the value property.

Example


let username =
document.getElementById("name").value;


console.log(username);



Checking Empty Fields

One of the most common validation tasks is checking whether required fields contain data.

Example


function validate()
{


let name =
document.getElementById("name").value;


if(name=="")
{

alert("Name is required");

return false;

}


}

Explanation


Using Form Events for Validation

JavaScript provides events that help perform validation when users interact with forms.

Common Form Events

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.

Preventing Form Submission

The preventDefault() method stops the default form submission process.

Example


form.addEventListener(
"submit",
function(event)
{

event.preventDefault();


});

This allows JavaScript to validate data before submitting the form.


Required Field Validation

Required field validation ensures that important fields are not left empty.

Example


function checkName()
{

let name =
document.getElementById("name").value;


if(name.length == 0)
{

return false;

}


return true;


}



Email Validation in JavaScript

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.


Basic Email Validation Example


function validateEmail()
{


let email =
document.getElementById("email").value;


if(email=="")
{

alert("Email is required");

return false;

}


else
{

alert("Email Accepted");

return true;

}


}


Email Validation Using Regular Expression

Regular Expression (Regex) is a pattern used to search and verify specific formats of text.

Example


function checkEmail()
{


let email =
document.getElementById("email").value;


let pattern =
 /^[^\s@]+@[^\s@]+\.[^\s@]+$/;


if(pattern.test(email))
{

alert("Valid Email");

}

else
{

alert("Invalid Email");

}


}

Explanation


Password Validation

Password validation ensures that users create secure passwords according to required rules.

A strong password generally contains:


Basic Password Length Validation


function checkPassword()
{


let password =
document.getElementById("password").value;


if(password.length < 6)
{

alert("Password must contain minimum 6 characters");

return false;

}


return true;


}


Password Strength Validation Using Regex


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

Confirm password validation checks whether the password and confirm password fields contain the same value.

Example


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

Mobile number validation checks whether the entered phone number contains the correct number of digits.

Example


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");

}


}


Number Validation

JavaScript can check whether a user entered a valid numeric value.

Example


let age =
document.getElementById("age").value;


if(isNaN(age))
{

alert("Please enter a number");

}



Displaying Error Messages

Good form validation should display clear messages near the incorrect input field instead of showing only alert boxes.

Example


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

Real-time validation checks user input while typing. It helps users correct mistakes immediately.

The input event is commonly used for real-time validation.

Example


input.addEventListener(
"input",
function()
{

console.log(input.value);


});



Form Validation Using Multiple Conditions

Real-world forms usually require multiple validation rules together.

Example


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 Validation Attributes

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.

Example Using Required Attribute


<input type="text" required>


The browser prevents submission when the field is empty.


Example Using Pattern Attribute


<input 
type="text"
pattern="[0-9]{10}"
>


This accepts only a 10-digit number.


Complete Registration Form Validation Example


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");


}



Advantages of Client-Side Validation


Limitations of Client-Side Validation


Best Practices for Form Validation



Complete Registration Form Validation Project

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.

Example


<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 Form Validation

Login forms use validation to ensure that users provide required credentials before authentication.

Example


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");


}



Displaying Error Messages Beside Fields

Professional websites usually display validation messages near the related input field instead of using alert boxes.

Example


<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>


Changing Error Message Style Using DOM

JavaScript can modify CSS styles to highlight invalid fields.

Example


let input =
document.getElementById("email");


input.style.border =
"2px solid red";


This technique improves user experience by visually showing incorrect fields.


Removing Error Styles


input.style.border =
"";


When the user enters correct information, the error style can be removed.


Password Strength Indicator

Many websites display password strength while users type passwords.

Example


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";

}


}



Using Regular Expressions in Validation

Regular expressions allow developers to create custom validation rules for different types of data.

Common Regex Patterns

Data Pattern Example
Mobile Number ^[0-9]{10}$
Only Letters ^[A-Za-z]+$
Username ^[A-Za-z0-9_]{5,}$
Email ^[^\s@]+@[^\s@]+\.[^\s@]+$

Validating Username


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");

}


}


Form Reset Handling

Sometimes developers need to clear form data after successful submission.

Example


document
.getElementById("form")
.reset();


The reset() method clears all form fields.


Preventing Incorrect Submission

The preventDefault() method allows developers to stop form submission until validation is completed.

Example


form.addEventListener(
"submit",
function(event)
{


if(validationFailed)
{

event.preventDefault();

}


});



Real-World Applications of Form Validation

JavaScript form validation is used in almost every interactive website.


Common Mistakes in JavaScript Form Validation


Best Practices for JavaScript Form Validation


JavaScript Form Validation Interview Questions

  1. What is form validation in JavaScript?
  2. Why is client-side validation used?
  3. Difference between client-side and server-side validation.
  4. How can JavaScript access form values?
  5. What is preventDefault() method?
  6. How do you validate an email using JavaScript?
  7. What are regular expressions?
  8. How do you check password strength?
  9. How can you display custom error messages?
  10. What is the difference between required attribute and JavaScript validation?
  11. How can you validate mobile numbers?
  12. How can you stop invalid form submission?
  13. What are HTML5 validation attributes?
  14. Why is server-side validation still required?
  15. How can DOM help in form validation?

Summary

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.


← Previous: DOM Manipulation Next: JavaScript Timers →
Home Visit Our YouTube Channel