Lesson 6: Real-World Application – Form Validation

Let’s enhance the Contact Form from Module 2 by adding validation.

HTML File

<form id="contactForm">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>
  <span id="errorMessage" style="color: red; display: none;">Please enter a valid email.</span>
  <br>
  <button type="submit">Send</button>
</form>

JavaScript File

document.getElementById('contactForm').addEventListener('submit', function(event) {
  const emailInput = document.getElementById('email');
  const errorMessage = document.getElementById('errorMessage');

  if (!emailInput.value.includes('@')) {
    event.preventDefault(); // Stop form submission
    errorMessage.style.display = 'inline';
  } else {
    errorMessage.style.display = 'none';
    alert('Form submitted successfully!');
  }
});

Key Takeaways from Module 4:

  1. JavaScript makes your website interactive and dynamic.
  2. Functions and events are core to responding to user actions.
  3. The DOM allows you to modify webpage content and styles.
  4. You’ve built an interactive webpage!

Next up is Module 5, where you’ll learn to combine everything to create a professional, responsive website. 🌐