Designing custom validation framework with async debounce
The plan outlines a vanilla JS form validator class leveraging setCustomValidity for sync and async checks, including a debounced username availability check that sets a "pending" UI state during async validation and updates validity and messages upon completion. It proposes a demonstration combining HTML, CSS for visual states, and JS with a debounced async validator integrated into a flexible validation framework.
Here's a minimal “framework‑style” wrapper around the native Constraint Validation API that lets you plug in synchronous and asynchronous validators. The async username check is debounced, marked as “pending”, and updates the UI when it completes.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom Validation + Async</title>
<style>
.field { margin: 1rem 0; }
.status { font-size: 0.9em; color: #888; }
.error { font-size: 0.9em; color: #d00; }
input.pending { border-color: orange; }
input:valid { border-color: green; }
input:invalid { border-color: red; }
</style>
</head>
<body>
<form id="signup" novalidate>
<div class="field">
<label>
Username
<input name="username" required minlength="3" maxlength="12">
</label>
<div class="status"></div>
<div class="error"></div>
</div>
<div class="field">
<label>
Email
<input type="email" name="email" required>
</label>
<div class="status"></div>
<div class="error"></div>
</div>
<button type="submit">Create account</button>
</form>
<script>
/* Small debounce helper */
function debounce(fn, delay = 300) {
let timer;
return function (...args) {
clearTimeout(timer);
return new Promise(resolve => {
timer = setTimeout(() => resolve(fn.apply(this, args)), delay);
});
};
}
/* Fake async username availability check */
function checkUsernameAvailability(name) {
// Simulate server latency
return new Promise(resolve => {
setTimeout(() => {
const taken = ['admin', 'root', 'user', 'test'];
resolve(!taken.includes(name.toLowerCase()));
}, 800);
});
}
/* The validation "framework" */
class FormValidator {
constructor(form, rules) {
this.form = form;
this.rules = rules;
form.setAttribute('novalidate', ''); // disable native bubble on submit
form.addEventListener('submit', e => {
e.preventDefault();
this.validateAll().then(valid => {
if (valid) {
alert('Form is valid and can be submitted!');
// form.submit();
} else {
form.reportValidity(); // let the browser show messages
}
});
});
// attach input handlers
Object.keys(rules).forEach(name => {
const input = form.elements[name];
if (input) {
input.addEventListener('input', () => this.validateField(name));
}
});
}
async validateField(name) {
const input = this.form.elements[name];
const validators = this.rules[name];
const fieldEl = input.closest('.field');
const statusEl = fieldEl.querySelector('.status');
const errorEl = fieldEl.querySelector('.error');
// reset previous state
input.setCustomValidity('');
input.classList.remove('pending');
statusEl.textContent = '';
errorEl.textContent = '';
for (const v of validators) {
if (v.async) {
// mark as pending while we wait
input.classList.add('pending');
statusEl.textContent = 'Checking…';
const msg = await v.validate(input);
input.classList.remove('pending');
statusEl.textContent = '';
if (msg) {
input.setCustomValidity(msg);
break;
}
} else {
const msg = v.validate(input);
if (msg) {
input.setCustomValidity(msg);
break;
}
}
}
// update UI
if (!input.validity.valid) {
errorEl.textContent = input.validationMessage;
}
return input.validity.valid;
}
async validateAll() {
const results = await Promise.all(
Object.keys(this.rules).map(name => this.validateField(name))
);
return results.every(Boolean);
}
}
/* Instantiate it for our form */
const form = document.getElementById('signup');
const debouncedAsyncUsernameValidator = {
async: true,
validate: debounce(async (input) => {
const value = input.value.trim();
if (!value) return 'Username is required';
if (value.length < 3) return 'At least 3 characters';
const available = await checkUsernameAvailability(value);
return available ? '' : 'That username is already taken';
}, 400)
};
const requiredValidator = {
validate: (input) => (input.validity.valueMissing ? 'This field is required' : '')
};
const emailValidator = {
validate: (input) => (input.validity.typeMismatch ? 'Enter a valid email address' : '')
};
new FormValidator(form, {
username: [requiredValidator, debouncedAsyncUsernameValidator],
email: [requiredValidator, emailValidator]
});
</script>
</body>
</html>
How it works:
- The
FormValidator wraps native setCustomValidity, checkValidity, and reportValidity.
- Validators are functions that return an error message (sync) or resolve to an error message (async). An empty string means “no error”.
- The async username validator is debounced so it only fires after typing stops for 400 ms. While it’s running, the input gets a
.pending class and a “Checking…” status.
- On completion,
setCustomValidity is called with either an empty string (available) or a message (taken). Native validity state and UI are updated accordingly.