Sep

17

PHP Regex - Validate Email Address

September 17, 2008 |

This article is for our friend Josh and all those who might be interested in knowing how to validate email address using PHP Regex (Regular Expression). The script below makes sure an e-mail address looks like a valid address, containing a username, @, and valid hostname. For example, null@example.com is valid, but NOSPAM@spam isn’t valid.

<html>
<head><title>4-11 Validating e-mail addresses</title></head>
<style>
    .err { color : red ; font-weight : bold }
</style>
<body>
<form action="recipe4-11.php" method="post">
<input type="text" name="input" /><br/>
<input type="submit" value="Submit Form" /><br/><br/>
<?php
if ( $_SERVER['REQUEST_METHOD'] == "POST" )
{
    $input = $_POST['input'];
    if ( preg_match( "/^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$/", $input ) )
    {
        # Do some processing here - input if valid
    }
    else
    {
        print "<span class=\"err\">Bad e-mail address. Please correct ".
            "and resubmit the form</span><br/>";
    }
}
?>
</form>
</body>
</html>


Regular Expression Explanation:

(

a group that includes

[A-z0-9]

a letter or number

[-A-z0-9]

a letter, number, or hyphen

\.

a literal dot or period

)

the end of the group

+

found one or more times

[A-z]

a letter

{2,4}

found between two and four times.



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

4 Comments so far

  1. zeriano on September 17, 2008 8:18 am

    Hi, thanks for sharing this script, the explanation about how PHP Regex work is very clear.

  2. gracie114 on September 17, 2008 8:21 am

    Hi, I agree with zeriano. PHP POSIX Regular Expression looks like gibberish to me, but with your code explanation, it’s very easy to understand.

  3. Aletheya on September 17, 2008 8:22 am

    Like most of your articles, clear, easy to read and comprehensive. :) keep it up!

  4. m0dk1d on September 17, 2008 8:23 am

    Love your script, hope to see more useful script from your site!

Sponsors




Links