On this page
HTML Form Validation (Client-Side)
HTML Form Validation (Client-Side)
This client-side form validation tutorial ties together everything learned so far — form elements, input types, and input attributes — to show how the browser validates data before it is ever sent to a server, and how to extend that validation with JavaScript.
What Is Client-Side Validation?
Client-side validation checks user input in the browser, instantly, before submission — improving user experience by catching mistakes early instead of waiting for a server round-trip. It should always be paired with server-side validation for security, since client-side checks can be bypassed.
Native HTML5 Validation
Simply using attributes like required, type="email", pattern, min, and max automatically enables free browser validation with zero JavaScript, as covered in the previous two topics.
The :valid and :invalid CSS Pseudo-Classes
You can style fields based on their validity state — a technique trending in modern sign-up form UX for real-time green/red visual feedback.
input:invalid {
border: 2px solid red;
}
input:valid {
border: 2px solid green;
}The Constraint Validation API (Trending: Custom Error Messages)
For full control, JavaScript's Constraint Validation API lets you write custom error messages and logic — a highly trending technique for polished, branded signup and checkout forms in 2026.
const input = document.querySelector('#email');
input.addEventListener('invalid', function(e) {
e.target.setCustomValidity('Please enter a valid email address!');
});
input.addEventListener('input', function(e) {
e.target.setCustomValidity('');
});Preventing Default Submission for Custom Validation
Combine event.preventDefault() with checkValidity() to fully control the submission flow with JavaScript.
form.addEventListener('submit', function(e) {
if (!form.checkValidity()) {
e.preventDefault();
alert('Please fix the errors before submitting.');
}
});Best Practices
- Always pair client-side validation with server-side validation
- Use
novalidateon the form only if you fully replace validation with JavaScript - Give clear, specific error messages, not just 'Invalid input'
- Use ARIA attributes like
aria-invalidfor accessibility
Live Example
Try submitting the form below with an empty or invalid email to see live custom validation messages.
Press Run to execute.
Press Run to execute.
Using the Constraint Validation API, add a custom error message to the password input that says 'Password must be at least 8 characters long' whenever it is invalid, and clear the message as the user types.
Press Run to execute.
Show expected output
passwordInput.addEventListener('invalid', ...) sets a custom message; passwordInput.addEventListener('input', ...) clears it via setCustomValidity('').This is a self-check — compare your result with the expected output above.
Was this page helpful?