
How to validate an email address in JavaScript
Validating the email address format in JavaScript with browser-based validation or custom logic.
To check if an email is valid using JavaScript, you can use the checkValidity() method from an <input type="email"> field (when checking in the browser environment) and additionally check for at
(@) symbol in the email address.
We are going to validate the email address format only using browser and custom validation, but not if the email actually exists.
The below code consists of two functions: isInputTypeSupported and isValidEmail. These functions are designed to validate input types and email addresses, leveraging the HTML5 form validation capabilities and custom logic for more comprehensive validation.
checkValidity method from an input type=”email”
When validating in the browser environment, we could utilize the checkValidity() method from an <input type="email">.
The checkValidity() method is used to determine if an input field is valid according to its constraints. For an <input type="email"> field, this means checking if the input is in a format that could potentially be a valid email address.
However, it’s important to understand that this method only checks if the input meets the basic criteria for an email format, such as containing an @
symbol, and does not verify if the email address actually exists or is correctly formatted beyond these basic rules.
The checkValidity() method returns true if the input is valid according to the constraints defined for the input field. For an email input, this means the input must contain an @
symbol, which is the basic requirement for an email address format.
For example, for the email test@example method checkValidity() returns true. Which should be fine as this email might be used inside the corporate network.
Validate an email address in JavaScript
Here’s a simple approach:
function isInputTypeSupported(type) {
const input = document.createElement('input');
input.setAttribute('type', type);
const invalidValue = 'not-a-date';
input.setAttribute('value', invalidValue);
return input.value !== invalidValue;
}
function isValidEmail(email) {
if (isInputTypeSupported('email')) {
const inputElement = document.createElement('input');
inputElement.type = 'email';
inputElement.value = email;
return inputElement.checkValidity();
}
const parts = email.split('@');
if (parts.length !== 2) {
return false;
}
if (parts[0].trim().length === 0 || parts[1].trim().length === 0) {
return false;
}
return true;
}The isValidEmail function combines the strengths of browser-based validation and custom logic to provide a robust validation mechanism. It first attempts to leverage the browser’s built-in validation capabilities for simplicity and efficiency. If that’s not possible or insufficient, it falls back to a more manual validation process to ensure that the email address meets the basic criteria for being considered valid.
Browser validation criteria
First, it checks if the browser supports the email input type using the isInputTypeSupported function. If the browser does support this type, it creates an input element of type email and sets its value to the provided email address. It then uses the checkValidity() method to determine if the email address is valid according to the browser’s validation rules. This method returns true if the email is valid and false otherwise.
The checkValidity method for an email input type checks for the following basic criteria:
- The input value must contain an
@symbol. - The input value must contain a string before the
@symbol (the local part of the email address). - The input value must contain a string after the
@symbol (the domain name). - The input value must contain a
.after the@symbol (to separate the domain name from the top-level domain). - The input value must not exceed the maximum allowed length.
Just a reminder that the checkValidity method does not verify whether the email address actually exists or is in use, it only checks for the basic syntax of an email address.
Custom validation
If the browser does not support the email input type, or if the checkValidity() method returns false, the function performs a custom validation. It splits the email address into two parts at the @
symbol and checks if both parts exist and are not empty. This simple check ensures that the email address has a local part and a domain part, which are basic requirements for an email address.
Avoiding a complex regular expression
An email address is formatted as local-part@domain, with the local-part up to 64 octets and the domain up to 255 octets. The formal definitions are in RFC 5322 (parts 3.2.3 and 3.4.1) and RFC 5321, with a more understandable form provided in RFC 3696.
There are many solutions out there that propose to use a regular expression, but in fact, the email can be constructed in so many ways that the creation of a regular expression is quite difficult and extremely error-prone.
Here is an example of a complex regular expression: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/. Even that does not guarantee that the validation of the email format is correct.
To avoid struggling with trying to validate all potential email formats, a simpler way is to just use a simple browser-based solution (when available) and a custom solution that checks only for the symbol @
and whitespaces. Leave the email existence verification for the server-side solutions.
Email format validation and verification of the actual existence of an email address are two different things.
How can you use a regular expression (regex) to check if a string is a valid email in JavaScript?
Although we recommend the lighter, @ + whitespace
check described above, there are situations, like quick front-end feedback, legacy code bases, or environments where you cannot reach the server, that make a regular expression test unavoidable. If you must use a regex, treat it as a best-effort filter, not a guarantee that the address actually exists or can receive mail.
The shortest pattern that catches the vast majority of real-world addresses without being unreadable is:
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(EMAIL_REGEX.test('alice@example.com')); // true
console.log(EMAIL_REGEX.test('bad@@example.com')); // falseThis only enforces three rules:
- Exactly one
@symbol. - Non-empty local part and domain.
- At least one dot after the
@.
It deliberately allows internationalised domains, sub-domains, plus addressing (user+tag@example.com), and other valid forms that stricter patterns often reject.
If you need to exclude IP-literal domains (e.g. user@[192.168.1.1]) or quoted strings, you can tighten it slightly:
const stricter =
/^[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])?)*$/;Even this still misses edge cases allowed by RFC 5322 (comments, obsolete forms, IPv6 literals) and accepts many addresses that do not exist. Therefore, whatever regex you choose, always:
- Re-validate on the server.
- Send a confirmation e-mail to prove deliverability.
- Keep the pattern in one place (a shared utility file) so you can swap it out later without hunting through templates.
Final note
It’s crucial to remember that this validation can be easily bypassed, and server-side validation is necessary to ensure data integrity and security. Validation like this can catch obvious mistakes but cannot guarantee that the email address is active or correctly formatted according to all the rules of the email specification.
Comments