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]" autocomplete="off" />
<button type="submit">Submit</button>
</form>
- The result: Enter a bad value and submit
OnSubmit novalidate
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.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.