Async Validation Patterns
What you'll learn: How to validate form input against a server (like checking if a username is already taken) without blocking the user interface.
Why Asynchronous Validation?
Sometimes validation can't happen instantly on the client side. You need to ask the server: "Is this username available?" or "Does this email already exist in our database?" These checks take time—the request travels to the server, the database is queried, and the response comes back. Meanwhile, your user is waiting.
Think of it like mailing a letter: You can't know the answer until the postal service delivers it and brings back a reply. You wouldn't freeze in place waiting—you'd go about your day until the response arrives.
The Basic Pattern
Async validation combines what you've learned: custom validation with setCustomValidity() and the Fetch API:
const usernameInput = document.querySelector('#username');
usernameInput.addEventListener('input', async (e) => {
const username = e.target.value;
if (username.length < 3) {
usernameInput.setCustomValidity('Username too short');
return;
}
// Check with server
const response = await fetch(`/api/check-username?name=${username}`);
const data = await response.json();
if (data.available) {
usernameInput.setCustomValidity(''); // Valid!
} else {
usernameInput.setCustomValidity('Username already taken');
}
});
Important Considerations
Debouncing: You don't want to hit the server on every keystroke. Wait until the user pauses typing (we'll learn debouncing techniques later).
User Feedback: Show a loading indicator while checking, so users know something is happening.
Error Handling: Network failures shouldn't block form submission permanently.
Key Takeaway: Async validation uses fetch() to check input against server data, then updates validity with setCustomValidity() based on the response—validating what only the server can know.