Back to Exercises
Full Code Used in This Demo
HTML
<form id="loginForm" class="form">
<div class="field">
<label for="email">Email</label>
<input id="email" name="email" type="email" placeholder="you@example.com">
<div id="err-email" class="error"></div>
</div>
<div class="field">
<label for="password">Password</label>
<input id="password" name="password" type="password" placeholder="••••••••">
<div id="err-password" class="error"></div>
</div>
<button class="btn" type="submit">Login</button>
<div id="result" class="result">Valid! Submitting...</div>
</form>
CSS
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; margin: 0; padding: 20px; background: #f8fafc; color: #0f172a; }
.form { max-width: 520px; }
.field { margin-bottom: 12px; }
.field label { display: block; margin-bottom: 6px; font-weight: 600; }
.field input { width: 100%; padding: 10px; border: 1px solid #cbd5e1; border-radius: 6px; }
.error { color: #dc2626; font-size: 13px; margin-top: 4px; min-height: 18px; }
.btn { display: inline-block; background: #3b82f6; color: #fff; border: none; border-radius: 8px; padding: 10px 14px; cursor: pointer; font-weight: 600; }
JavaScript
const form = document.getElementById('loginForm');
const errEmail = document.getElementById('err-email');
const errPass = document.getElementById('err-password');
const result = document.getElementById('result');
function validateEmail(email) {
const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return pattern.test(email);
}
form.addEventListener('submit', function(e) {
e.preventDefault();
errEmail.textContent = '';
errPass.textContent = '';
result.style.display = 'none';
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
let ok = true;
if (!validateEmail(email)) { errEmail.textContent = 'Invalid email'; ok = false; }
if (!password) { errPass.textContent = 'Password is required'; ok = false; }
if (ok) { result.style.display = 'block'; }
});