Form validation
Interactive live demo and source code tabs for Form validation:
/apps/machine-coding/form-validation/index.html Open standalone ↗
document.addEventListener('DOMContentLoaded', () => { const form = document.getElementById('signup-form'); const alertBox = document.getElementById('alert-box');
const fields = { fullName: document.getElementById('fullName'), email: document.getElementById('email'), password: document.getElementById('password'), confirmPassword: document.getElementById('confirmPassword'), terms: document.getElementById('terms'), };
const errors = { fullName: document.getElementById('fullName-error'), email: document.getElementById('email-error'), password: document.getElementById('password-error'), confirmPassword: document.getElementById('confirmPassword-error'), terms: document.getElementById('terms-error'), };
function validateField(name) { let error = ''; const val = fields[name].type === 'checkbox' ? fields[name].checked : fields[name].value.trim();
switch (name) { case 'fullName': if (!val) error = 'Full name is required.'; else if (val.length < 3) error = 'Name must be at least 3 characters.'; break; case 'email': if (!val) error = 'Email is required.'; else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)) error = 'Please enter a valid email address.'; break; case 'password': if (!val) error = 'Password is required.'; else if (val.length < 8) error = 'Password must be at least 8 characters.'; else if (!/\d/.test(val)) error = 'Password must contain at least one number.'; break; case 'confirmPassword': if (!val) error = 'Please confirm your password.'; else if (val !== fields.password.value.trim()) error = 'Passwords do not match.'; break; case 'terms': if (!val) error = 'You must accept the terms and conditions.'; break; }
errors[name].textContent = error; if (error && fields[name].classList) { fields[name].classList.add('invalid'); } else if (fields[name].classList) { fields[name].classList.remove('invalid'); }
return !error; }
// Real-time listener Object.keys(fields).forEach((name) => { fields[name].addEventListener('input', () => validateField(name)); fields[name].addEventListener('blur', () => validateField(name)); });
form.addEventListener('submit', (e) => { e.preventDefault(); alertBox.classList.add('hidden');
const isValid = Object.keys(fields).reduce((acc, name) => { const valid = validateField(name); return acc && valid; }, true);
if (isValid) { alertBox.textContent = '🎉 Form submitted successfully! (Controlled state & validation passed)'; alertBox.className = 'alert success'; } });
document.getElementById('reset-btn').addEventListener('click', () => { form.reset(); alertBox.classList.add('hidden'); Object.keys(errors).forEach((name) => { errors[name].textContent = ''; if (fields[name].classList) fields[name].classList.remove('invalid'); }); });});<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>React Form Validation Demo</title> <link rel="stylesheet" href="style.css" /></head><body> <div class="container"> <h2>Interactive Form Validation</h2> <p class="subtitle">Practice controlled inputs, validation rules, error handling, and feedback.</p>
<div id="alert-box" class="alert hidden"></div>
<form id="signup-form" novalidate> <div class="form-group"> <label for="fullName">Full Name</label> <input type="text" id="fullName" placeholder="John Doe" /> <span class="error-msg" id="fullName-error"></span> </div>
<div class="form-group"> <label for="email">Email Address</label> <input type="email" id="email" placeholder="john@example.com" /> <span class="error-msg" id="email-error"></span> </div>
<div class="form-group"> <label for="password">Password</label> <input type="password" id="password" placeholder="At least 8 characters, 1 number" /> <span class="error-msg" id="password-error"></span> </div>
<div class="form-group"> <label for="confirmPassword">Confirm Password</label> <input type="password" id="confirmPassword" placeholder="Re-enter password" /> <span class="error-msg" id="confirmPassword-error"></span> </div>
<div class="form-group checkbox-group"> <label> <input type="checkbox" id="terms" /> I agree to the Terms and Conditions </label> <span class="error-msg" id="terms-error"></span> </div>
<div class="actions"> <button type="submit" id="submit-btn">Submit Registration</button> <button type="button" id="reset-btn" class="secondary-btn">Reset Form</button> </div> </form> </div>
<script src="index.js"></script></body></html>* { box-sizing: border-box; margin: 0; padding: 0;}
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #0f172a; color: #f8fafc; display: flex; justify-content: center; align-items: center; min-height: 100vh; padding: 20px;}
.container { background: #1e293b; padding: 2rem; border-radius: 12px; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4); width: 100%; max-width: 480px; border: 1px solid #334155;}
h2 { font-size: 1.5rem; margin-bottom: 0.5rem; color: #38bdf8;}
.subtitle { font-size: 0.875rem; color: #94a3b8; margin-bottom: 1.5rem;}
.form-group { margin-bottom: 1.25rem; display: flex; flex-direction: column;}
label { font-size: 0.875rem; font-weight: 600; margin-bottom: 0.5rem; color: #e2e8f0;}
input[type="text"],input[type="email"],input[type="password"] { padding: 0.75rem; border-radius: 6px; border: 1px solid #475569; background: #0f172a; color: #f8fafc; font-size: 0.95rem; outline: none; transition: border-color 0.2s;}
input:focus { border-color: #38bdf8;}
input.invalid { border-color: #ef4444;}
.checkbox-group label { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; font-weight: normal;}
.error-msg { color: #f87171; font-size: 0.8rem; margin-top: 0.35rem; min-height: 1.1rem;}
.actions { display: flex; gap: 0.75rem; margin-top: 1.5rem;}
button { flex: 1; padding: 0.75rem; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; transition: background 0.2s;}
#submit-btn { background: #0284c7; color: white;}
#submit-btn:hover { background: #0369a1;}
.secondary-btn { background: #334155; color: #e2e8f0;}
.secondary-btn:hover { background: #475569;}
.alert { padding: 0.75rem 1rem; border-radius: 6px; margin-bottom: 1.25rem; font-size: 0.9rem;}
.alert.success { background: rgba(34, 197, 94, 0.2); border: 1px solid #22c55e; color: #4ade80;}
.alert.hidden { display: none;}