Published
January 28, 2023
Updated
Here are some notes on Custom JS techniques for advanced forms validation.
Adding Event Listeners for Validation
Use JavaScript to attach event listeners (blur
, input
, or submit
) to the fields or form:
blur
: Validate when the user leaves a field.input
: Validate as the user types.submit
: Validate before the form is submitted.
document.querySelector('form').addEventListener('submit', (event) => {
if (!validateCustomRules()) {
event.preventDefault(); // Prevent form submission
}
});
Using Custom Validation Functions
Create custom functions to validate specific rules.
For example:
function validateCustomRules() {
const inputField = document.querySelector('#username');
const errorMessage = document.querySelector('#username-error');
if (inputField.value.length < 5) {
errorMessage.textContent = 'Username must be at least 5 characters long.';
inputField.classList.add('invalid');
return false;
}
errorMessage.textContent = '';
inputField.classList.remove('invalid');
return true;
}
Leveraging the Constraint Validation API
Modern browsers provide the Constraint Validation API
for custom validation while integrating with the native validation system.
Example: Using setCustomValidity
const inputField = document.querySelector('#username');
inputField.addEventListener('input', () => {
if (inputField.value.length < 5) {
inputField.setCustomValidity('Username must be at least 5 characters long.');
} else {
inputField.setCustomValidity(''); // Clear the error
}
});
Check Overall Validity
document.querySelector('form').addEventListener('submit', (event) => {
if (!event.target.checkValidity()) {
event.preventDefault(); // Prevent submission
}
});
Real-Time Validation Feedback
Use JavaScript to provide instant feedback using CSS classes.
const inputField = document.querySelector('#username');
inputField.addEventListener('input', () => {
if (inputField.value.length < 5) {
inputField.classList.add('invalid');
inputField.classList.remove('valid');
} else {
inputField.classList.add('valid');
inputField.classList.remove('invalid');
}
});
CSS for Styling Feedback
input.valid {
border: 2px solid green;
}
input.invalid {
border: 2px solid red;
}
Grouping Validation Logic
For forms with multiple fields, create a centralized validation handler.
function validateForm() {
const usernameField = document.querySelector('#username');
const passwordField = document.querySelector('#password');
let isValid = true;
if (usernameField.value.length < 5) {
showError(usernameField, 'Username must be at least 5 characters long.');
isValid = false;
} else {
clearError(usernameField);
}
if (passwordField.value.length < 8) {
showError(passwordField, 'Password must be at least 8 characters long.');
isValid = false;
} else {
clearError(passwordField);
}
return isValid;
}
function showError(input, message) {
const error = input.nextElementSibling; // Assume an error span exists
error.textContent = message;
input.classList.add('invalid');
}
function clearError(input) {
const error = input.nextElementSibling; // Assume an error span exists
error.textContent = '';
input.classList.remove('invalid');
}
Validation Before Submission
If you prefer validation to occur only when the user submits the form:
document.querySelector('form').addEventListener('submit', (event) => {
if (!validateForm()) {
event.preventDefault(); // Prevent submission if validation fails
}
});
Example: Custom Email Validation
If you need a custom validation beyond type="email"
, use a regular expression:
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
document.querySelector('#email').addEventListener('blur', (event) => {
const emailField = event.target;
if (!validateEmail(emailField.value)) {
emailField.setCustomValidity('Please enter a valid email address.');
} else {
emailField.setCustomValidity('');
}
});
Best Practices
- Use Native Validation When Possible: Combine native HTML5 attributes (
required
,pattern
, etc.) with custom validations. - Graceful Degradation: Ensure the form works with JavaScript disabled (native attributes provide basic validation).
- Avoid Inline Scripts: Use external or inline scripts in
<script>
tags for better maintainability. - Integrate with Accessibility: Use
aria-live
regions oraria-describedby
for informing users about validation messages.
Example Form
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<span id="username-error" class="error"></span>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<span id="password-error" class="error"></span>
<button type="submit">Submit</button>
</form>
With JavaScript, you can extend form validation capabilities while keeping it user-friendly and accessible.