How to Validate an Email Address in JavaScript

Email validation is an important aspect of web development, as it ensures that the data submitted by users is in the correct format and reduces the risk of errors. In this article, we will explore how to validate an email address in JavaScript.

Using Regular Expressions

Regular expressions (regex) can be used to validate email addresses in JavaScript. A regex pattern can be created to match the standard format of an email address. Let's take a look at an example:

            
                function validateEmail(email) {
                    const regex = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
                    return regex.test(email);
                }
                
                const email = "[email protected]";
                const isValid = validateEmail(email);
                console.log(isValid);
                // Output: true
            
        

In the above example, we define a function validateEmail that takes an email address as a parameter. The regex pattern /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/ is used to match the email address format.

  • ^[\w-]+: Matches one or more word characters or hyphens at the start of the address.
  • (\.[\w-]+)*: Matches zero or more occurrences of a period followed by one or more word characters or hyphens.
  • @: Matches the "@" symbol.
  • ([\w-]+\.)+: Matches one or more occurrences of one or more word characters or hyphens followed by a period.
  • [a-zA-Z]{2,7}$: Matches 2 to 7 uppercase or lowercase letters at the end of the address.

The test() method is used to check if the provided email address matches the regex pattern. If it does, the function returns true; otherwise, it returns false.

Using HTML5 Input Type

In addition to using regex, you can also use the HTML5 input element with the type="email" attribute to validate email addresses. This attribute tells the browser to enforce email validation on the input field.

            
                <input type="email" id="email">
                <button onclick="validateEmail()">Validate</button>

                <script>
                    function validateEmail() {
                        const emailInput = document.getElementById("email");
                        console.log(emailInput.checkValidity());
                        // Output: true or false
                    }
                </script>
            
        

In the above example, the input element is defined with the type="email" attribute. The checkValidity() method is used to check if the entered email address is valid or not. It returns true if the email is valid, and false otherwise.

Adding Feedback to the User

When validating an email address, it is helpful to provide feedback to the user about whether their input is valid or not. This can be done by displaying an error message or changing the styling of the input field.

            
                <input type="email" id="email">
                <span id="emailError" style="color: red; display: none;">Invalid email address.</span>
                <button onclick="validateEmail()">Validate</button>

                <script>
                    function validateEmail() {
                        const emailInput = document.getElementById("email");
                        const emailError = document.getElementById("emailError");

                        if (emailInput.checkValidity()) {
                            emailError.style.display = "none";
                            console.log("Email is valid.");
                        } else {
                            emailError.style.display = "block";
                            console.log("Invalid email.");
                        }
                    }
                </script>
            
        

In this example, a span element is added to display an error message when the email address is invalid. The display property is set to none initially to hide the error message. If the email address is invalid, the display property is changed to block to show the error message.