Forms allow users to enter information into a website. For example, a registration form may collect a username, email address, password and mobile number. Before this information is processed, the application should check whether the entered values are complete and follow the required rules.
JavaScript Form Validation is the process of checking form data in the browser before it is submitted. JavaScript can detect missing values, incorrect formats and invalid combinations and can provide feedback to the user immediately.
Form validation is commonly used in registration forms, login pages, contact forms, admission applications, search forms, checkout pages and many other interactive websites.
Form validation means checking whether the information entered into a form satisfies predefined requirements.
For example, a registration form may require a username, a properly formatted email address and a password with a minimum length. If one of these requirements is not satisfied, the form can display an appropriate error message instead of continuing with invalid data.
Validation improves the quality of information submitted through a form. It also helps users identify mistakes before they continue to the next step.
| Purpose | How Validation Helps |
|---|---|
| Data Quality | Helps prevent incomplete or incorrectly formatted input. |
| User Experience | Provides feedback while the user is completing the form. |
| Error Detection | Identifies common input mistakes before submission. |
| Application Logic | Ensures that required values are available before processing. |
Form validation can be performed in the browser, on the server, or at both levels.
| Validation Type | Where It Runs | Main Purpose |
|---|---|---|
| Client-Side Validation | Web Browser | Provides immediate feedback and catches common input errors. |
| Server-Side Validation | Web Server | Performs authoritative validation before accepting or processing data. |
Client-side validation should not be treated as a security mechanism. A user can bypass browser-side JavaScript or send requests without using the page. Important data must therefore be validated again on the server.
Before using JavaScript, we need an HTML form containing input elements.
<form id="registrationForm">
<label>Name</label>
<input type="text" id="name">
<label>Email</label>
<input type="email" id="email">
<button type="submit">Submit</button>
</form>
The id attribute allows JavaScript to locate a particular input element.
The value property is used to read the information entered into an input field.
let name = document.getElementById("name").value;
console.log(name);
If the user enters Rahul, the variable name contains the value "Rahul".
One of the simplest validation rules is checking whether a required field contains a value.
let name = document.getElementById("name").value;
if(name.trim() === "")
{
alert("Name is required");
}
The trim() method removes unnecessary spaces from the beginning and end of a string. It is useful because an input containing only spaces should normally be treated as empty.
The submit event is triggered when the user submits a form. It is generally a better place for complete form validation than attaching validation only to a button click.
let form = document.getElementById("registrationForm");
form.addEventListener("submit", function(event)
{
event.preventDefault();
console.log("Form submitted");
});
The preventDefault() method stops the browser's default submission action. This gives JavaScript an opportunity to validate the data first.
function validateName()
{
let name = document.getElementById("name").value;
if(name.trim() === "")
{
alert("Please enter your name");
return false;
}
return true;
}
The function returns false when the validation fails and true when the value is acceptable.
HTML provides an email input type that performs basic browser-level checking. JavaScript can also be used when an application needs additional rules.
let email = document.getElementById("email").value;
if(email.trim() === "")
{
alert("Email is required");
}
let email = document.getElementById("email").value;
let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if(pattern.test(email))
{
console.log("Valid email");
}
else
{
console.log("Invalid email");
}
The test() method checks whether the supplied string matches the regular expression and returns a Boolean value.
Regular expressions can be useful for basic format checking, but email validation should not attempt to reproduce every rule of the complete email specification.
Password validation checks whether a password satisfies the application's requirements.
let password = document.getElementById("password").value;
if(password.length < 8)
{
alert("Password must contain at least 8 characters");
}
let password = document.getElementById("password").value;
let pattern =
/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$/;
if(pattern.test(password))
{
console.log("Password meets the required rules");
}
else
{
console.log("Password does not meet the required rules");
}
The example requires at least eight characters, including an uppercase letter, a lowercase letter and a number. Password requirements should be chosen according to the application's security needs rather than using a single universal rule.
Registration forms often ask users to enter their password twice. JavaScript can compare both values.
let password =
document.getElementById("password").value;
let confirmPassword =
document.getElementById("confirmPassword").value;
if(password !== confirmPassword)
{
alert("Passwords do not match");
}
The strict inequality operator !== is appropriate here because both values should contain exactly the same string.
A mobile number rule depends on the country and application. For an example that expects exactly ten digits, a regular expression can be used.
let mobile = document.getElementById("mobile").value;
let pattern = /^[0-9]{10}$/;
if(pattern.test(mobile))
{
console.log("Valid mobile number");
}
else
{
console.log("Enter a 10-digit mobile number");
}
When a form expects a numeric value, JavaScript can check whether the supplied value can be interpreted as a number.
let age = document.getElementById("age").value;
if(age.trim() === "" || Number.isNaN(Number(age)))
{
alert("Please enter a valid number");
}
Converting the input with Number() makes the intended numeric check explicit.
Using alert boxes for every validation error can make a form difficult to use. A better approach is to display the message near the related input.
<input type="text" id="name"> <span id="nameError"></span>
JavaScript can then update the message:
let name = document.getElementById("name").value;
let error = document.getElementById("nameError");
if(name.trim() === "")
{
error.textContent = "Name is required";
}
else
{
error.textContent = "";
}
The textContent property is suitable for inserting plain validation messages without interpreting the message as HTML.
A form can also provide visual feedback by adding a CSS class to an invalid input.
let input = document.getElementById("email");
input.classList.add("invalid");
When the value becomes valid, the class can be removed.
input.classList.remove("invalid");
Using CSS classes is generally cleaner than repeatedly changing individual style properties from JavaScript.
Sometimes validation is performed while the user is entering information. The input event is useful for this purpose.
let password =
document.getElementById("password");
password.addEventListener("input", function()
{
console.log(password.value.length);
});
Real-time validation can be useful for password requirements, character limits and other feedback where the user benefits from immediate information.
| Event | Purpose |
|---|---|
| submit | Occurs when the form is submitted. |
| input | Occurs when the value of an input changes as the user enters data. |
| change | Occurs when an element's value changes and the change is committed. |
| focus | Occurs when an element receives focus. |
| blur | Occurs when an element loses focus. |
JavaScript is not the only way to validate forms. Modern HTML provides several built-in validation features.
| Attribute | Purpose |
|---|---|
| required | Requires the user to provide a value. |
| minlength | Specifies the minimum number of characters. |
| maxlength | Specifies the maximum number of characters. |
| min | Specifies the minimum numeric value. |
| max | Specifies the maximum numeric value. |
| pattern | Defines a regular-expression pattern for supported input types. |
<input
type="text"
id="username"
required
minlength="5"
maxlength="20"
>
The browser can automatically check these constraints before allowing a normal form submission to continue.
JavaScript can also use the browser's built-in constraint validation system.
let form = document.getElementById("registrationForm");
if(form.checkValidity())
{
console.log("Form is valid");
}
else
{
console.log("Form contains invalid data");
}
The checkValidity() method returns true when the form satisfies its validation constraints and false otherwise.
The following example combines several concepts into one practical registration form. It validates the username, email, password and confirmation password before allowing the submission to continue.
<form id="registrationForm">
<label>Username</label>
<input type="text" id="username" required>
<label>Email</label>
<input type="email" id="email" required>
<label>Password</label>
<input type="password" id="password" required>
<label>Confirm Password</label>
<input type="password" id="confirmPassword" required>
<button type="submit">Register</button>
</form>
<script>
const form =
document.getElementById("registrationForm");
form.addEventListener("submit", function(event)
{
const username =
document.getElementById("username").value.trim();
const email =
document.getElementById("email").value.trim();
const password =
document.getElementById("password").value;
const confirmPassword =
document.getElementById("confirmPassword").value;
const emailPattern =
/^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if(username === "")
{
alert("Please enter username");
event.preventDefault();
return;
}
if(!emailPattern.test(email))
{
alert("Please enter a valid email address");
event.preventDefault();
return;
}
if(password.length < 8)
{
alert("Password must contain at least 8 characters");
event.preventDefault();
return;
}
if(password !== confirmPassword)
{
alert("Passwords do not match");
event.preventDefault();
return;
}
alert("Form validation successful");
});
</script>
In a real application, successful client-side validation would normally be followed by sending the form data to a server for further validation and processing.
The reset() method can be used to restore a form to its initial state.
document
.getElementById("registrationForm")
.reset();
This can be useful when a user wants to clear the form or when an application needs to reset the interface after a particular action.
The preventDefault() method is commonly used when custom JavaScript validation is performed during the submit event.
form.addEventListener("submit", function(event)
{
if(validationFailed)
{
event.preventDefault();
}
});
If validation succeeds, the application can allow the normal submission process or send the data using an appropriate API request.
For applications that accept important or sensitive information, the server should independently validate the received data before storing or processing it.
| Mistake | Better Approach |
|---|---|
| Checking only whether a field is empty | Validate the format and business rules required by the application. |
| Using only client-side validation | Perform server-side validation as well. |
| Showing generic error messages | Explain which field needs correction. |
| Repeating the same validation code | Create reusable validation functions where appropriate. |
| Ignoring whitespace | Use methods such as trim() where appropriate. |
| Using complicated regular expressions unnecessarily | Use patterns that match the actual requirement of the application. |
Form validation is useful anywhere a website accepts structured information from users.
JavaScript Form Validation is the process of checking user-entered form data in the browser before it is submitted or processed.
The preventDefault() method stops the browser's default action for an event. During form validation, it can prevent submission when the entered data is invalid.
No. Client-side validation can be bypassed, so important data must also be validated on the server.
JavaScript can access an input element and read its value property.
let value =
document.getElementById("name").value;
A regular expression is a pattern used to search for or validate text according to defined rules.
Read both input values and compare them using the strict inequality or equality operators.
if(password !== confirmPassword)
{
// Passwords are different
}
The checkValidity() method checks whether an element or form satisfies its built-in HTML validation constraints.
JavaScript Form Validation helps developers check user input before it is processed. Common validation tasks include checking required fields, validating email formats, checking password requirements, comparing passwords, validating numbers and displaying useful error messages.
JavaScript can work together with HTML5 validation features such as required, minlength, maxlength, min, max and pattern. Events such as submit and input can be used to control when validation takes place.
Client-side validation improves the user experience, but it is not a replacement for server-side validation. A reliable web application should validate important data on the server before accepting, storing or processing it.