Spot the bug - #71

Can you spot the form bug?

<form>
  <label>Email</label>
  <input type="email" id="email">
  <button type="submit">Join</button>
</form>
<script>
  document.querySelector('form').addEventListener('submit', (e) => {
    if (!email.value.includes('@')) alert('invalid');
  });
</script>

Reply with what is broken and how you would fix it.

Your submit handler never cancels the submit, so you’ll still post/navigate even after yelling “invalid” (and depending on the browser, email being a magic global from id="email" is flaky). Grab the element explicitly and call preventDefault() when it’s bad.

const emailEl = document.getElementById('email');
document.querySelector('form').addEventListener('submit', (e) => {
  if (!emailEl.value.includes('@')) {
    e.preventDefault();
    alert('invalid');
  }
});

Tradeoff: you’re duplicating what type="email" already does, so I’d usually lean on native validation unless you need custom rules/messages.