Why Not Use HTML5 Validation?
HTML5 has built-in validation with required, type="email", and pattern. But browser-native validation:
- ✓Looks different in every browser (inconsistent UX)
- ✓Cannot show errors in a custom location
- ✓Cannot validate complex rules like password strength
- ✓Cannot do real-time validation as the user types
Custom JavaScript validation solves all of these.
The Core Pattern
Every field follows this pattern:
- ✓An
<input>element - ✓A
<span>below it for the error message - ✓A JavaScript function that checks the value and toggles
.valid/.invalidclasses
<div class="field-group">
<label for="email">Email <span class="required">*</span></label>
<input type="email" id="email" />
<span class="error-msg" id="email-error">Enter a valid email</span>
</div>
Email Validation
function validateEmail() {
const field = document.getElementById('email');
const error = document.getElementById('email-error');
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!field.value.trim()) {
showError(field, error, 'Email is required');
return false;
}
if (!regex.test(field.value)) {
showError(field, error, 'Enter a valid email address');
return false;
}
showValid(field, error);
return true;
}
Password Strength Meter
Check multiple rules and score the password:
function getStrength(password) {
let score = 0;
if (password.length >= 8) score++;
if (/[A-Z]/.test(password)) score++;
if (/[a-z]/.test(password)) score++;
if (/[0-9]/.test(password)) score++;
if (/[^A-Za-z0-9]/.test(password)) score++;
return score; // 0–5
}
Run All Validators on Submit
form.addEventListener('submit', (e) => {
e.preventDefault();
const results = [
validateRequired('name', 'name-error', 'Name'),
validateEmail(),
validatePassword(),
validateConfirm(),
];
if (results.every(r => r === true)) {
showSuccessState();
}
});
This is a preview. The full ebook covers 8 field types — including phone number, number range, select dropdown, and checkbox — plus real-time validation on the
inputevent and the blur-first pattern for better UX.
