How can I validate an email address in JavaScript?

Category
Stack Overflow
Author
Thomas KowalskiThomas Kowalski

In today’s world, email addresses and providers have become commonplace, and most organizations and systems have implemented them as the medium of communication and the identity of users. But what is an email address or an email?

Email is short for electronic mail and is used to exchange digital messages over the Internet. To receive or send an email, one must have a unique email address protected by some password or encryption. An email address is a unique identifier used to send and receive emails. Just like a physical home address allows postal workers to deliver physical stuff to your doorsteps, the email address is virtual, allowing another email address to send you electronic stuff.

An email address has a unique structure that allows the email servers to identify valid email addresses. An email address is structured as a string of ASCII characters separated by an @ character into the local (personal) and domain parts.

The rule for a valid email address is personalpart@domainpart

The local part is to the left of the @ symbol and is usually used to present the user’s personal information. This part is supposed to be unique to the associated domain, so no two users in the domain have the same local part. The personal part has the following can contain the following:

  • Uppercase and lowercase letters (A-Z and a-z)
  • Numeric characters (0-9)
  • Special characters – ! # $ % & ‘ * + – / = ? ^ _ ` { | } ~
  • Period, dot, or full stop (.) with the condition that it cannot be the first or last letter of the email and cannot repeat one after another.

The domain part is to the right of the @ symbol and specifies the mail server domain used to receive and store emails for that specific local part. In most cases, the domain part is the website domain name of the email hosting service provider. However, the domain part can include subdomains.

A valid domain name can be up to 63 characters (letters, numbers, or combination) long plus the 4 characters used to identify the domain extension (.com, .net, .org). The only symbol character domain names can include is a hyphen (-), although the domain name cannot start or end with a hyphen nor have consecutive hyphens. Common symbols such as asterisks (*), underscores (_), and exclamation points (!) are not allowed.

Why use JavaScript for Email Address Validation?

JavaScript is often preferred for email validation because it can be executed on the client-side using the browser, meaning the validation can be performed in real-time as the user fills out the form. This provides immediate feedback to the user if they enter an invalid email address, improving user experience and reducing the likelihood of errors.

Furthermore, JavaScript provides powerful regular expression capabilities, well-suited for validating email addresses. Regular expressions allow for complex pattern matching, which is necessary for checking the various requirements of a valid email address, such as the format of the personal and domain parts, the presence of the “@” symbol, and the validity of the top-level domain.

What are the main methods of email validation in JavaScript?

As stated, email addresses are complex ASCII patterns that must be checked. Using regular expressions is the best method of validating these email addresses in JavaScript.

Consider the following JavaScript code. The code checks for invalid email addresses and returns a message to tell what is wrong with the entered email address.

function validateEmail() {
    const emailInput = document.getElementById("emailInput");
    const validationMessage = document.getElementById("validationMessage");
    const email = emailInput.value.trim();

    // Check if email is empty
    if (email === "") {
        validationMessage.innerText = "Please enter an email address";
        return false;
    }

    // Check if email is valid
    const emailParts = email.split("@");
    if (emailParts.length !== 2) {
        validationMessage.innerText = "Please enter a valid email address - missing or too many '@' symbols";
        return false;
    }

    const localPart = emailParts[0];
    const domainPart = emailParts[1];

    // Check local part for invalid characters
    const localPartRegex = /^[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+(\.[a-zA-Z0-9!#$%&'*+\-/=?^_`{|}~]+)*$/;
    if (!localPartRegex.test(localPart)) {
        validationMessage.innerText = "Please enter a valid email address - invalid characters in local part";
        return false;
    }

    // Check local part for consecutive periods
    if (localPart.includes("..")) {
        validationMessage.innerText = "Please enter a valid email address - consecutive periods in local part";
        return false;
    }

    // Check local part for leading or trailing period
    if (localPart.startsWith(".") || localPart.endsWith(".")) {
        validationMessage.innerText = "Please enter a valid email address - leading or trailing period in local part";
        return false;
    }

    // Check domain part for invalid characters
    const domainPartRegex = /^[a-zA-Z0-9.-]+$/;
    if (!domainPartRegex.test(domainPart)) {
        validationMessage.innerText = "Please enter a valid email address - invalid characters in domain part";
        return false;
    }

    // Check domain part for consecutive hyphens
    if (domainPart.includes("--")) {
        validationMessage.innerText = "Please enter a valid email address - consecutive hyphens in domain part";
        return false;
    }

    // Check domain part for leading or trailing hyphen
    if (domainPart.startsWith("-") || domainPart.endsWith("-")) {
        validationMessage.innerText = "Please enter a valid email address - leading or trailing hyphen in domain part";
        return false;
    }

    // Check domain part for valid TLD
    const tldRegex = /^[a-zA-Z]{2,}$/;
    const domainParts = domainPart.split(".");
    if (domainParts.length < 2 || !tldRegex.test(domainParts[domainParts.length - 1])) {
        validationMessage.innerText = "Please enter a valid email address - invalid top-level domain";
        return false;
    }

    // Email is valid
    validationMessage.innerText = "Email is valid!";
    return true;
}

It has the following checks:

  • Empty email: “”
  • Invalid email (missing “@”): “testemail.com”
  • Invalid email (too many “@”): ” testemail @com@org”
  • Invalid email (invalid characters in local part): “[email protected]
  • Invalid email (consecutive periods in local part): “x..man@ testemail.com”
  • Invalid email (leading period in local part): “.xman@ testemail.com”
  • Invalid email (invalid characters in domain part): “xman@test_email.com”
  • Invalid email (consecutive hyphens in domain part): “example@test–email.com”
  • Invalid email (leading hyphen in domain part): “[email protected]
  • Invalid email (trailing hyphen in domain part): “[email protected]
  • Invalid email (invalid top-level domain): “[email protected]
  • Valid email: [email protected]

Advanced Validation Methods

Besides regular expressions, other validation steps can be used to verify emails. Domain checks to verify that the domain exists and accepts emails, email verification by sending a confirmation email for the user to verify they have access to it or checking for disposable email providers, and using a checklist to exclude such email addresses can go a long way in validating them.

Conclusion

In conclusion, Javascript is a powerful language that can be used to validate email addresses and give live feedback to the user on the browser on what is a valid or invalid email address.

The complete code for email validation, including the HTML, JavaScript, and CSS are attached.

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Email Validation Form</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="container">
            <form>
                <h3>Email Validation Form</h3>
                <label for="emailInput">Email:</label>
                <input type="text" id="emailInput" name="emailInput">
                <button type="button" onclick="validateEmail()">Submit</button>
                <div id="validationMessage"></div>
            </form>
        </div>
        <script src="emailValidation.js"></script>
    </body>
</html>

CSS

body {
    font-family: Arial, sans-serif;
    background-color: #f2f2f2;
}

.container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

form {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: #fff;
    border-radius: 5px;
    padding: 20px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

h3 {
    margin-top: 0;
}

label {
    margin-bottom: 10px;
}

input[type="text"] {
    padding: 10px;
    border-radius: 5px;
    border: none;
    margin-bottom: 10px;
    background-color: #fff;
}

button[type="button"] {
    padding: 10px;
    border-radius: 5px;
    border: none;
    background-color: #4CAF50;
    color: #fff;
    cursor: pointer;
}

button[type="button"]:hover {
    background-color: #3e8e41;
}

#validationMessage {
    margin-top: 10px;
    font-weight: bold;
    color: #ff0000;
}

.valid {
    background-color: #c8f7c5;
    color: #008000;
}

.invalid {
    background-color: #f7c5c5;
    color: #ff0000;
}