Simple email validation in JavaScript | Example code

The Simplest email validation in JavaScript can done by using Regular Expression.

var mailformat = /^\[email protected][a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; 

Simplest email validation Example in JavaScript

To get a valid email id we use a regular expression. Here is complete HTML code:-

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function ValidateEmail(inputText)
        {
            var mailformat = /^\[email protected][a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; 
            if(inputText.value.match(mailformat))
            {
                alert("Valid email address!");
                return true;
            }
            else
            {
                alert("Invalid email address!");
                return false;
            }
        }
    </script>
</head>
<body>


    <form name="form1" action="#">
        <input type='text' name='text1'/>

        <input type="submit" name="submit" value="Submit" onclick="ValidateEmail(document.form1.text1)"/>
    </form>

</body>
</html>

Output:

Simplest email validation Example in JavaScript

Q: Is it possible email id validation in JavaScript without regular expression?

Answer: Let’s try it without regex, first rules you stated as well as not allowing @ to start the address and not allowing . to end the address. It does not account for multiple . in the address.

function testEmailAddress(emailToTest) {
    // check for @
    var atSymbol = emailToTest.indexOf("@");
    if(atSymbol < 1) return false;

    var dot = emailToTest.indexOf(".");
    if(dot <= atSymbol + 2) return false;

    // check that the dot is not at the end
    if (dot === emailToTest.length - 1) return false;

    return true;
}

Do comment if you have another simple example or way to do it. Doubts and suggestion are always welcome.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.