JavaScript Email Validation Using Regular Expression | PHP Tutorials for Beginners

It is the simple code to help you create a form with email validation using a regular expression. The function checks the email field against a regex pattern and shows an alert if the format is invalid.

Complete Example

<html>
<head>
<title>JavaScript Email Validation Using Regular Expression</title>
<script type="text/javascript">
    function Validate(input) {
        var format = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

        if (document.getElementById("email").value.match(format)) {
            document.myform.email.focus();
            return true;
        } else {
            alert("You have entered a wrong email address!");
            document.myform.email.focus();
            return false;
        }
    }
</script>
</head>
<body>
    <h2>Input an email and Submit</h2>
    <form name="myform" action="#">
        <input type="text" name="email" id="email" />
        <input type="submit" name="submit" value="Submit"
               onclick="Validate(document.myform.email)" />
    </form>
</body>
</html>

How the Regex Works

The regular expression pattern /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ checks that:

  • The local part (before @) contains word characters, dots, or hyphens.
  • There is exactly one @ symbol.
  • The domain contains word characters, dots, or hyphens.
  • The TLD (e.g. .com, .net) is 2–3 characters long.

Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.

← Older Post Newer Post →