Form Validation is a foundational responsibility of client-side JavaScript. It verifies that user inputs satisfy data integrity requirements (such as valid email formats, strong passwords, and required fields) before dispatching network payloads to backend servers.
// Select form and input fields
const signupForm = document.getElementById("registration-form");
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const errorBox = document.getElementById("error-summary");
signupForm.addEventListener("submit", (e) => {
// 1. Prevent default form submission reload
e.preventDefault();
const errors = [];
// 2. Validate Email Format using RegEx
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(emailInput.value.trim())) {
errors.push("Please provide a valid email address (e.g., user@domain.com).");
}
// 3. Validate Password Strength (Min 8 chars, 1 digit, 1 special character)
const passwordPattern = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
if (!passwordPattern.test(passwordInput.value)) {
errors.push("Password must be at least 8 characters with at least 1 number and 1 special symbol.");
}
// 4. Render Feedback or Proceed
if (errors.length > 0) {
errorBox.innerHTML = errors.map(err => `<p class="text-danger">${err}</p>`).join("");
errorBox.classList.remove("hidden");
} else {
errorBox.classList.add("hidden");
console.log("Validation Successful! Dispatching payload to server...");
// Call backend API via fetch()
}
});
Exam Question: "What are the events triggered during form input in JavaScript?"
input: Fires synchronously on every keystroke or character change (best for real-time validation meters).change: Fires only after the user leaves the input field (on blur) if the value was altered.focus / blur: Fires when an input gains or loses keyboard focus.submit: Fires on the form element when the user triggers submission.How does JavaScript interact with the browser window itself (navigation, URLs, history)? Proceed to: JavaScript Browser Object Model (BOM) →
Accelerate your JavaScript mastery by studying these tightly connected core tutorials:
Validating email, phone numbers, and passwords.
Handling change, blur, and submit events.
Displaying inline validation error messages.