codegurukool.com · Free coding tutorials & online compiler

Home › JavaScript Tutorial › Form validation

Form validation

Check input before accepting it.

Listen for the submit event, call preventDefault() to stop the page reloading, then check the values and show a clear message.

Example code

<form id="f"><input id="e" placeholder="Email"> <button>Join</button></form>
<p id="m"></p>
<script>
  f.addEventListener("submit", e => {
    e.preventDefault();
    const ok = /^\S+@\S+\.\S+$/.test(document.getElementById("e").value);
    m.textContent = ok ? "Thanks!" : "Enter a valid email, like you@mail.com";
  });
</script>

Run this code in the online editor

← TimersClasses and errors →