Mini-Build: Form Validation UI
Build a complete form validation system with real-time feedback — field-level validation, error messages, button state management, and submit handling. Combines all DOM and event concepts from this module.
Form Validator Features
- Real-time validation — Validate each field as user types (input event)
- Field-level errors — Show error message under each invalid field
- Visual feedback — Red border for errors, green for valid
- Submit control — Disable submit button until all fields valid
- FormData collection — Collect and display form data on valid submit
Form Validator Code
// Complete Form Validator
class FormValidator {
constructor() {
this.fields = {};
this.errors = {};
}
addField(name, value, rules) {
this.fields[name] = value;
this.validateField(name, value, rules);
}
validateField(name, value, rules) {
this.errors[name] = [];
if (rules.required && !value.trim()) {
this.errors[name].push(`${name} is required`);
}
if (rules.minLength && value.length < rules.minLength) {
this.errors[name].push(`${name} must be at least ${rules.minLength} characters`);
}
if (rules.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
this.errors[name].push("Invalid email format");
}
if (rules.match && value !== rules.match.value) {
this.errors[name].push(`${name} must match ${rules.match.name}`);
}
return this.errors[name].length === 0;
}
get isValid() {
return Object.values(this.errors).every(errs => errs.length === 0);
}
getErrors() {
const allErrors = {};
for (const [field, errs] of Object.entries(this.errors)) {
if (errs.length > 0) allErrors[field] = errs;
}
return allErrors;
}
}
// Demo usage
const validator = new FormValidator();
// Simulate form fields
validator.addField("Name", "Al", { required: true, minLength: 3 });
validator.addField("Email", "alice@email.com", { required: true, email: true });
validator.addField("Password", "12345", { required: true, minLength: 8 });
console.log("Is form valid?", validator.isValid); // false
console.log("\n❌ Errors:");
const errors = validator.getErrors();
Object.entries(errors).forEach(([field, errs]) => {
errs.forEach(err => console.log(` ${field}: ${err}`));
});
// Fix errors and re-validate
validator.addField("Name", "Alice", { required: true, minLength: 3 });
validator.addField("Password", "securePass123", { required: true, minLength: 8 });
console.log("\n✅ After fixing:");
console.log("Is form valid?", validator.isValid); // true
console.log("Form data:", validator.fields);Tip
Tip
This form project combines every DOM concept: selection (querySelector), manipulation (textContent, classList), events (submit, input), delegation, and validation. Build projects like this to solidify your DOM skills before learning React.
HTML5 validation = zero JavaScript — the browser handles it
Common Mistake
Warning
Using innerHTML to insert user input creates XSS attack vectors. In this form project, always use textContent or createElement to display user-provided data safely. Never trust user input.
Practice Task
Note
Extend the form: (1) Add a phone number field with format validation. (2) Add a dropdown for country selection. (3) Add a 'terms and conditions' checkbox that must be checked. (4) Save form data to localStorage and restore on page reload.
Quick Quiz
Key Takeaways
- Build a complete form validation system with real-time feedback — field-level validation, error messages, button state management, and submit handling.
- Real-time validation — Validate each field as user types (input event)
- Field-level errors — Show error message under each invalid field
- Visual feedback — Red border for errors, green for valid