Table of Contents

How to get and validate an email address with an HTML form?

About

This article shows you how to handle a email address into a form via an input element

Step by step

The default email type

In HTML, they already have an email type in a input element.

name is the name of the form variable. We choose email but it can be anything you want.

Example:

<input type="email" name="email" placeholder="[email protected]" />

The HTML built-in validation

The sections below will show how to validate the email via the built-in validation.

OnSubmit

The validation will happen when the user submit the form.

<form>
  <input type="email" name="email" placeholder="[email protected]" autocomplete="off" />
  <button type="submit">Submit</button>
</form>

OnSubmit novalidate

In this validation, we take over the validation of the form with the novalidate form attribute

<form novalidate>
  <input type="email" name="email" placeholder="[email protected]"/>
  <button type="submit">Submit</button>
</form>
document.querySelector("form")
  .addEventListener("submit", (event) => {
     event.preventDefault();
     const emailInput = event.target.email;
     const emailValid = emailInput.validity.valid;
     if(emailValid){
       console.log(`valid: ${emailInput.value}`);
     } else {
       console.log(`invalid: ${emailInput.value}`);
     }
  })

OnInput

This example shows you live validation when the user enters the value thanks to the input event

<input type="email" name="email" placeholder="[email protected]" />
document.querySelector('input[type="email"]')
  .addEventListener("input", (event) => {
    // event.target is the input element
    // You may also use `event.target.validity.typeMismatch`
    if (event.target.validity.valid) {
      console.log(`invalid: ${event.target.value}`);
    } else {
      console.log(`valid: ${event.target.value}`);
    }
});