JavaScript Form Validation
Form validation checks user input before it gets sent to a server. It catches mistakes — like an empty name field or a badly formatted email — right in the browser, giving the user instant feedback without a page reload. JavaScript gives you full control over what counts as valid input and how errors are shown.
Why Validate on the Client Side?
Server-side validation is essential for security, but client-side validation improves the user experience by catching mistakes immediately. The user does not have to wait for a server round-trip to learn that their email is missing an "@" symbol.
Diagram: Validation Flow
User fills form → clicks Submit
│
[ JavaScript Validation ]
│
Pass? YES → form data sent to server
Pass? NO → show error messages, stop submission
Basic HTML Form Setup
<form id="signup-form">
<input type="text" id="name" placeholder="Full Name">
<input type="email" id="email" placeholder="Email">
<input type="password" id="password" placeholder="Password">
<p id="error-msg" style="color:red;"></p>
<button type="submit">Sign Up</button>
</form>
Preventing Default Submission
When a form is submitted, the browser normally sends data and reloads the page. Call event.preventDefault() to stop this and run your own validation first.
let form = document.getElementById("signup-form");
form.addEventListener("submit", function(event) {
event.preventDefault(); // stop default page reload
validateForm();
});
Validating Individual Fields
Check for Empty Fields
function isEmpty(value) {
return value.trim() === "";
}
let name = document.getElementById("name").value;
if (isEmpty(name)) {
showError("Name cannot be empty.");
}
Check Email Format
A regular expression checks whether the email contains the required structure — characters, @, a domain, and a dot.
function isValidEmail(email) {
let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
let email = document.getElementById("email").value;
if (!isValidEmail(email)) {
showError("Please enter a valid email address.");
}
Diagram: Email Validation Pattern
Valid: user@mail.com → passes
a.b@x.co.in → passes
Invalid: user@ → fails (no domain)
@mail.com → fails (no local part)
usermail.com → fails (no @)
user @mail.com → fails (space)
Check Password Length
function isStrongPassword(password) {
return password.length >= 8;
}
let password = document.getElementById("password").value;
if (!isStrongPassword(password)) {
showError("Password must be at least 8 characters.");
}
Full Validation Function
function validateForm() {
let name = document.getElementById("name").value.trim();
let email = document.getElementById("email").value.trim();
let password = document.getElementById("password").value;
let errorMsg = document.getElementById("error-msg");
// Clear previous errors
errorMsg.textContent = "";
if (name === "") {
errorMsg.textContent = "Name is required.";
return;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errorMsg.textContent = "Enter a valid email address.";
return;
}
if (password.length < 8) {
errorMsg.textContent = "Password must be at least 8 characters.";
return;
}
// All checks passed
errorMsg.style.color = "green";
errorMsg.textContent = "Form submitted successfully!";
}
Diagram: Validation Order
Submit clicked │ ├─ Is name empty? YES → show error, stop │ ├─ Is email invalid? YES → show error, stop │ ├─ Is password short? YES → show error, stop │ └─ All valid → submit!
Real-Time Validation (On Input)
Validate as the user types — give feedback instantly instead of waiting for submission.
let emailInput = document.getElementById("email");
let emailError = document.getElementById("email-error");
emailInput.addEventListener("input", function() {
let val = emailInput.value.trim();
if (val === "") {
emailError.textContent = "";
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)) {
emailError.textContent = "Invalid email format.";
emailError.style.color = "red";
} else {
emailError.textContent = "✓ Looks good!";
emailError.style.color = "green";
}
});
Confirm Password Match
let password = document.getElementById("password").value;
let confirm = document.getElementById("confirm-password").value;
if (password !== confirm) {
showError("Passwords do not match.");
return;
}
Using HTML5 Built-In Validation Attributes
HTML5 provides built-in validation attributes that work alongside JavaScript validation.
<input type="text" required minlength="2" maxlength="50">
<input type="email" required>
<input type="number" min="1" max="100">
<input type="url" required>
Use novalidate on the form element when you want JavaScript to handle all validation logic and suppress the browser's built-in popups.
<form id="signup-form" novalidate>...</form>
Showing Errors Per Field
Place a small error message below each input field for better user experience.
<div class="field">
<input type="text" id="username" placeholder="Username">
<span class="field-error" id="username-error"></span>
</div>
function setError(fieldId, message) {
document.getElementById(fieldId + "-error").textContent = message;
}
function clearError(fieldId) {
document.getElementById(fieldId + "-error").textContent = "";
}
// Usage
setError("username", "Username is required.");
clearError("username");
Diagram: Field-Level Error Display
┌────────────────────────────────┐ │ [ Username input field ] │ │ ⚠ Username is required. │ ← red error below field └────────────────────────────────┘ ┌────────────────────────────────┐ │ [ Email input field ] │ │ ✓ Looks good! │ ← green confirmation └────────────────────────────────┘
Common Validation Patterns
| Check | Code Pattern |
|---|---|
| Required field | value.trim() === "" |
| Email format | /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value) |
| Minimum length | value.length < 8 |
| Only letters | /^[a-zA-Z]+$/.test(value) |
| Phone (10 digits) | /^\d{10}$/.test(value) |
| Passwords match | password === confirm |
Summary
JavaScript form validation intercepts form submission, checks every field against rules, displays helpful error messages, and only allows submission when everything passes. Use event.preventDefault() to stop the form from submitting before validation is complete. Validate on submit for a final check and on input for real-time feedback. Always combine client-side validation with server-side validation — the server is the final line of defense for data integrity and security.
