Validations in JavaScript — Form Validation Guide
Validations
It is very important to pre-validate the forms before submission as they can have inappropriate values. JavaScript provides the facility to validate the form on the client-side so data processing will be faster than server-side validation.
Client-side validation should be treated as a user-experience feature, not a security boundary. Users can disable JavaScript, modify requests, or call your API directly, so the server must validate the same rules again before saving data.
Form Validations Examples
function validate() {
const form = document.forms.myForm;
const name = form.name.value.trim();
const email = form.email.value.trim();
const password = form.password.value;
if (name === "") {
alert("Please enter your name.");
form.name.focus();
return false;
}
if (email === "") {
alert("Please enter your email.");
form.email.focus();
return false;
}
if (password.length < 8) {
alert("Please enter a password with at least 8 characters.");
form.password.focus();
return false;
}
return true;
}
The old-style example above returns false to stop form submission. For new projects, prefer addEventListener(), clear error messages near each field, and the HTML5 Constraint Validation API when possible.
Complete Accessible Form Validation
A good validation flow tells users what went wrong, places the message near the input, and exposes the message to screen readers. The example below uses aria-describedby in HTML and writes the error text into matching message elements.
<form id="signupForm" novalidate>
<label for="email">Email</label>
<input id="email" name="email" type="email" aria-describedby="emailError">
<small id="emailError" class="error" aria-live="polite"></small>
<label for="password">Password</label>
<input id="password" name="password" type="password" aria-describedby="passwordError">
<small id="passwordError" class="error" aria-live="polite"></small>
<button type="submit">Create account</button>
</form>const form = document.querySelector("#signupForm");
const email = document.querySelector("#email");
const password = document.querySelector("#password");
function showError(input, message) {
const error = document.querySelector(`#${input.id}Error`);
input.setAttribute("aria-invalid", "true");
error.textContent = message;
}
function clearError(input) {
const error = document.querySelector(`#${input.id}Error`);
input.removeAttribute("aria-invalid");
error.textContent = "";
}
form.addEventListener("submit", function (event) {
let isValid = true;
clearError(email);
clearError(password);
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value.trim())) {
showError(email, "Enter a valid email address.");
isValid = false;
}
if (password.value.length < 8) {
showError(password, "Password must be at least 8 characters.");
isValid = false;
}
if (!isValid) {
event.preventDefault();
}
});Regex-Based Validation
Regular expressions provide powerful pattern matching for validating emails, phone numbers, URLs, and more.
// Email validation
function isValidEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
console.log(isValidEmail('user@example.com')); // true
console.log(isValidEmail('invalid-email')); // false
// Phone number (10 digits)
function isValidPhone(phone) {
return /^\d{10}$/.test(phone);
}
console.log(isValidPhone('9876543210')); // true
// Strong password: min 8 chars, uppercase, lowercase, digit, special char
function isStrongPassword(pwd) {
return /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/.test(pwd);
}
console.log(isStrongPassword('Secure@123')); // true
console.log(isStrongPassword('weak')); // false
// URL validation
function isValidURL(url) {
try {
new URL(url);
return true;
} catch {
return false;
}
}
console.log(isValidURL('https://tutorialslogic.com')); // true
Validation Checklist
HTML5 Constraint Validation API
Modern browsers provide a built-in Constraint Validation API that works alongside HTML5 form attributes like required, minlength, pattern, and type.
const form = document.getElementById('myForm');
const emailInput = document.getElementById('email');
form.addEventListener('submit', function(e) {
e.preventDefault();
// Check validity using built-in API
if (!emailInput.validity.valid) {
if (emailInput.validity.valueMissing) {
emailInput.setCustomValidity('Email is required.');
} else if (emailInput.validity.typeMismatch) {
emailInput.setCustomValidity('Please enter a valid email address.');
}
emailInput.reportValidity();
return;
}
// Clear custom message and submit
emailInput.setCustomValidity('');
console.log('Form is valid, submitting...');
});
// Real-time validation feedback
emailInput.addEventListener('input', function() {
if (this.validity.valid) {
this.classList.remove('is-invalid');
this.classList.add('is-valid');
} else {
this.classList.remove('is-valid');
this.classList.add('is-invalid');
}
});
- Client-side validation improves UX but never replace server-side validation - always validate on both sides.
- Use regex patterns for email, phone, and password validation.
- The HTML5 Constraint Validation API (validity, setCustomValidity, reportValidity) provides built-in validation without extra libraries.
- Use event.preventDefault() to stop form submission and run your own validation logic.
- Provide clear, specific error messages - tell users exactly what is wrong and how to fix it.
- Real-time validation (on input event) gives immediate feedback as users type.
Level Up Your Javascript Skills
Master Javascript with these hand-picked resources