intermediate

Form Validation

Validate form inputs before submission.

Form validation ensures data quality and improves user experience. This exercise teaches you client-side validation techniques, pattern matching with regex, and providing helpful user feedback.

πŸ“š Concepts & Theory

Form validation is critical for data integrity and user experience. JavaScript provides multiple ways to validate form inputs before submission.

Understanding Form Validation:

Why Validate?

  • Prevent invalid data submission

  • Improve user experience with immediate feedback

  • Reduce server load

  • Enhance security (client-side first, server-side always)
Validation Strategies:

1. HTML5 Native Validation:

<input type="email" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$">

2. JavaScript Validation:

Prevent Form Submission:

form.addEventListener("submit", (e) => {
e.preventDefault(); // Stop default submission

if (validateForm()) {
form.submit(); // Manual submit if valid
}
});

Check Input Values:

const email = document.getElementById("email").value;

if (email.trim() === "") {
showError("Email is required");
return false;
}

if (!isValidEmail(email)) {
showError("Invalid email format");
return false;
}

Email Validation:

function isValidEmail(email) {
const regex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;
return regex.test(email);
}

Password Validation:

function isStrongPassword(password) {
return password.length >= 8 &&
/[A-Z]/.test(password) && // Has uppercase
/[a-z]/.test(password) && // Has lowercase
/[0-9]/.test(password); // Has number
}

Common Validation Patterns:

Required Field:

if (input.value.trim() === "") {
input.classList.add("error");
return false;
}

Length Validation:

if (input.value.length < 8) {
showError("Minimum 8 characters");
return false;
}

Pattern Matching:

const phoneRegex = /^\\d{3}-\\d{3}-\\d{4}$/;
if (!phoneRegex.test(phone.value)) {
showError("Format: 123-456-7890");
return false;
}

Real-Time Validation:

input.addEventListener("input", () => {
if (isValid(input.value)) {
input.classList.remove("error");
input.classList.add("success");
} else {
input.classList.add("error");
input.classList.remove("success");
}
});

Best Practices:

  • βœ… Always validate on server too (client-side can be bypassed)

  • βœ… Show clear, helpful error messages

  • βœ… Validate on submit AND real-time

  • βœ… Use appropriate input types (email, number, tel)

  • βœ… Provide visual feedback (colors, icons)

  • βœ… Focus first invalid field

  • ❌ Don't block paste functionality

  • ❌ Don't overvalidate (be reasonable)

🎯 Your Challenge

Validate that email field is not empty.

πŸ“ Starter Code

JavaScript
// HTML: <form id="myForm"><input id="email"><button>Submit</button></form>

function validateForm() {
  // Your code here
}
  • Listen for the 'submit' event on the form
  • Use e.preventDefault() to stop default submission
  • Get input values with input.value
  • Check if required fields are not empty
  • Validate format with regex or length checks
  • Show error messages if validation fails

Solution

JavaScript
function validateForm() {
  const form = document.getElementById('myForm');
  const email = document.getElementById('email');
  
  form.addEventListener('submit', (e) => {
    if (!email.value.trim()) {
      e.preventDefault();
      alert('Email is required!');
    }
  });
}

validateForm();

Explanation

This solution validates form inputs before allowing submission by: 1) Adding a submit event listener to the form, 2) Calling preventDefault() to stop default submission, 3) Checking input values against validation rules (required, format, length), 4) Displaying error messages or highlighting invalid fields, 5) Only submitting if all validations pass. The preventDefault() method is crucialβ€”it stops the browser from submitting the form until JavaScript approves. Real-world forms should validate both client-side (UX) and server-side (security).

⚠️ Common Mistakes to Avoid

  • Forgetting e.preventDefault() (form submits anyway)
  • Only validating on client (must validate server-side too)
  • Poor error messages ('Invalid input' vs 'Email must contain @')
  • Not trimming whitespace from inputs
  • Blocking form submission permanently after error
  • Not resetting error state when user corrects input

❓ Frequently Asked Questions

To stop the form from submitting until JavaScript validates all inputs and gives approval.
No! Always validate on both client (UX) and server (security). Client-side can be bypassed.
Either on blur (field loses focus), on input (real-time), or on submit. Combination of blur + submit is common.
Add error classes to inputs, display error spans/divs, or use HTML5 setCustomValidity().

πŸ”— Related Exercises