HTML 5 added some new input types, including email (<input type="email" name="email" />
). However, you may not wish to use the browser’s native validation and implement your own with JavaScript. There are so many different ways to validate an email with JavaScript so choosing a way to do it can be difficult. I personally like using the HTML 5 input approach but want to use my own validation.
Fortunately, we just just look at the specification for the HTML 5 email input and use that regex.
This code allows emails such as user@localhost and is not Unicode — which may not be suitable for your application
function validateEmail(email) {
// regex taken from https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
return re.test(email);
}
