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.

  • The form
<form>
  <input type="email" name="email" placeholder="[email protected]" />
  <button type="submit">Submit</button>
</form>
  • The result: Enter a bad value and submit

OnSubmit nnvalidate

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

  • The form with the novalidate form attribute
<form novalidate>
  <input type="email" name="email" placeholder="[email protected]"/>
  <button type="submit">Submit</button>
</form>
  • The javascript
document.querySelector("form")
  .addEventListener("submit", (event) => {
     event.preventDefault();
     const emailInput = event.target.querySelector('input[name="email"]');
     const emailValid = emailInput.validity.valid;
     if(emailValid){
       console.log(`valid: ${emailInput.value}`);
     } else {
       console.log(`invalid: ${emailInput.value}`);
     }
  })
  • The result:
    • Submit with no value and see that the value is valid in the absence of the required validation attribute
    • Enter a value and submit

OnInput

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

  • The HTML
<input type="email" name="email" placeholder="[email protected]" />
  • The javascript
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}`);
    }
});
  • The result: Enter a value, it will be validated.





Discover More
HTML - Form Validation

This page is form validation in HTML. The javascript counterpart is called the constraint validation API . In short, you set standard HTML attributes that constrain the possible value of form elements....
What are HTML Input Elements?

An inputinput element of a form control that permits to define a scalar value (single value) inputFull list Ref Doc The type attribute defined: the default behavior the design of the element....



Share this page:
Follow us:
Task Runner