Solved

php email validation for subdomain

Posted on 2013-05-28
15
598 Views
Last Modified: 2013-06-28
1> test@mail.e-treo.biz
2> @mail.e-treo.biz

I want to validate such email ids using regex in php.
username may / may not be present.

currently i am using below regex pattern .
preg_match('/^[a-z0-9\-\_\.]*@[a-z0-9\-]+[\.(a-z)+]+$/', $restContent)

but it fails to validate such emails with subdomains
0
Comment
Question by:Insoftservice
  • 6
  • 5
  • 4
15 Comments
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 39200798
This might help

define('regx_email', '/^[\!-\-\/-\~]*(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');

preg_match(regx_email, $restContent);

I modified the below (which requires a name)

define('regx_email', '/^[\!-\-\/-\~]+(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');
0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39200814
i have tried this one it worked  but i am not so confident to use it

preg_match('/^[.\w-]*@([\w-]+\.)+[a-zA-Z]{2,6}$/', $restContent)
0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39200839
Tried your code replacing my regex pattern but it failed
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 55

Expert Comment

by:Julian Hansen
ID: 39200882
failed how?

This worked for me
define('regx_email', '/^[\!-\-\/-\~]+(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');

$email = "test@mail.e-treo.biz";

$matches = preg_match(regx_email, $email);
echo "Matches $matches on $email<br/>";

$email = "@mail.e-treo.biz";
$matches = preg_match(regx_email, $email);
echo "Matches $matches on $email<br/>";

Open in new window

Output
Matches 1 on test@mail.e-treo.biz
Matches 1 on @mail.e-treo.biz

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39201181
Here is how I validate an email address.  PHP has a built-in function for this, so you do not need to write your own.  Please treat this as untested code -- I have not tested it with your examples.

<?php // RAY_email_validation.php
error_reporting(E_ALL);


// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE
// SEE MAN PAGE: http://php.net/manual/en/intro.filter.php
function check_valid_email($email, $rout=TRUE)
{
    // LIST OF BLOCKED DOMAINS
    $bogus = array
    ( '@unknown.com'
    , '@example.com'
    , '@gooseball.org'
    )
    ;

    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER
    if (strnatcmp(phpversion(),'5.2') >= 0)
    {
        if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) return FALSE;
    }

    // IF LOWER-LEVEL PHP, WE CAN CONSTRUCT A REGULAR EXPRESSION
    else
    {
        $regex
        = '/'                        // START REGEX DELIMITER
        . '^'                        // START STRING
        . '[A-Z0-9_-]'               // AN EMAIL - SOME CHARACTER(S)
        . '[A-Z0-9._-]*'             // AN EMAIL - SOME CHARACTER(S) PERMITS DOT
        . '@'                        // A SINGLE AT-SIGN
        . '([A-Z0-9][A-Z0-9-]*\.)+'  // A DOMAIN NAME PERMITS DOT, ENDS DOT
        . '[A-Z\.]'                  // A TOP-LEVEL DOMAIN PERMITS DOT
        . '{2,6}'                    // TLD LENGTH >= 2 AND =< 6
        . '$'                        // ENDOF STRING
        . '/'                        // ENDOF REGEX DELIMITER
        . 'i'                        // CASE INSENSITIVE
        ;
        // TEST THE STRING FORMAT
        if (!preg_match($regex, $email)) return FALSE;
    }

    // TEST TO SEE IF THE DOMAIN IS IN OUR BLOCKED LIST
    foreach ($bogus as $badguy)
    {
        if (stripos($email, $badguy)) return FALSE;
    }

    // FILTER_VAR OR PREG_MATCH DOES NOT TEST IF THE DOMAIN IS ROUTABLE
    if ($rout)
    {
        $domain = explode('@', $email);

        // MAN PAGE: http://php.net/manual/en/function.checkdnsrr.php
        if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") ) return TRUE;

        // EMAIL IS NOT ROUTABLE
        return FALSE;
    }
    return TRUE;
}



// DEMONSTRATE THE FUNCTION IN ACTION
$e = NULL;
if (!empty($_GET["e"]))
{
    $e = $_GET["e"];
    if (check_valid_email($e))
    {
        echo "<br/>VALID: $e \n";
    }
    else
    {
        echo "<br/>BOGUS: $e \n";
    }
}


// END OF PROCESSING - CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<form>
TEST A STRING FOR A VALID EMAIL ADDRESS:
<input name="e" value="$e" />
<input type="submit" />
</form>
ENDFORM;

echo $form;

Open in new window

Best to all, ~Ray
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39201286
Now that I have tested it, here are the results.  

The email address $email = 'test@mail.e-treo.biz'; is valid, but the domain name 'mail.e-treo.biz' is not routable per checkdnsrr().  

The email address '@mail.e-treo.biz' is invalid (and this makes sense because it is missing the username before the '@').  

The domain 'e-treo.biz' is unroutable.

If all you want to do is check for a well-formed domain name (which is really all you've got with something like '@mail.e-treo.biz') you might try prepending the letter "X" to the string if the string starts with '@'.   Trim() the string before testing the substr($email,0,1) == '@'.  If needed, add the "X" to the front of the string and then call the built-in PHP validation filter.

Here is the test script.

<?php // RAY_temp_foo.php
error_reporting(E_ALL);
echo '<pre>';


$email = 'test@mail.e-treo.biz';

echo PHP_EOL . "EMAIL: $email";
echo PHP_EOL;
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
    echo "$email IS BOGUS";
} else echo "Email is OK";
echo PHP_EOL;

$domain = explode('@', $email);

if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
{
    echo "$email IS ROUTABLE";
} else echo $domain[1] . " IS NOT ROUTABLE PER CheckDNSRR()";
echo PHP_EOL;


$email = '@mail.e-treo.biz';

echo PHP_EOL . "EMAIL: $email";
echo PHP_EOL;
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
    echo "$email IS BOGUS";
} else echo "Email is OK";
echo PHP_EOL;

$domain = explode('@', $email);

if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
{
    echo "$email IS ROUTABLE";
} else echo $domain[1] . " IS NOT ROUTABLE PER CheckDNSRR()";
echo PHP_EOL;


$email = 'test@e-treo.biz';

echo PHP_EOL . "EMAIL: $email";
echo PHP_EOL;
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
    echo "$email IS BOGUS";
} else echo "Email is OK";
echo PHP_EOL;

$domain = explode('@', $email);

if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
{
    echo "$email IS ROUTABLE";
} else echo $domain[1] . " IS NOT ROUTABLE PER CheckDNSRR()";
echo PHP_EOL;


$email = '@mail.e-treo.biz';

echo PHP_EOL . "EMAIL: $email";
echo PHP_EOL;
if (substr(trim($email), 0, 1) == '@') $email = 'X' . $email;

if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
{
    echo "$email IS BOGUS";
} else echo "Email is OK";
echo PHP_EOL;

$domain = explode('@', $email);

if ( checkdnsrr($domain[1], "MX") || checkdnsrr($domain[1], "A") )
{
    echo "$email IS ROUTABLE";
} else echo $domain[1] . " IS NOT ROUTABLE PER CheckDNSRR()";
echo PHP_EOL;

Open in new window

0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39204021
@Ray the domain name is just an example. And its not the actual domain.
I would test both the example provide by you and @ julianH
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39204244
the domain name is just an example
Please learn about the SSCCE.  There is no way I could have known your data set provided with the question was hypothetical and bogus, and it look a lot of time to figure out why I kept seeing consistent failures from all the tests.  If you had added a note showing that you expected the validation to fail for the domain name you provided it would have been helpful!

In any case, this question is fully answered with tested and working code samples, so I'll sign off on it now.  Best of luck with your project, ~Ray
0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39214500
@Ray first of all question is not bogus.
I can't provide my clients domain name for testing your php code.
I had requested for validation and not to check whether we could send mails to the concern mails.
pls check my email id. 1> test@mail.e-treo.biz.
Where it specifies its test mail.
actual domain is similar to the mail provided.
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 39215440
@insoftservice - did you see my last post - how did my suggestion fail on your side?
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 39215964
pls check my email id. 1> test@mail.e-treo.biz.
I did that already.  I checked all of the test data provided.  I posted the results.  Please see this link:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28140356.html#a39201286

There was a detailed explanation of what I found, including this:

The email address $email = 'test@mail.e-treo.biz'; is valid, but the domain name 'mail.e-treo.biz' is not routable per checkdnsrr().

0
 
LVL 15

Author Comment

by:Insoftservice
ID: 39218058
hi @julianH i have pasted ur code as below check the o/p


define('regx_email', '/^[\!-\-\/-\~]+(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');

$email = "test@mail.e-treo.biz";

$matches = preg_match(regx_email, $email);
echo "Matches $matches on $email<br/>";

$email = "@mail.e-treo.biz";
$matches = preg_match(regx_email, $email);
echo "Matches $matches on $email<br/>";

$email = "@.biz";
$matches = preg_match(regx_email, $email);
echo "match failed $matches on $email<br/>


o/p

Matches 1 on test@mail.e-treo.biz
Matches 0 on @mail.e-treo.biz
match failed 0 on @.biz


I might have done some mistake.
0
 
LVL 55

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 39218154
Posted wrong expression - change first + to a *

define('regx_email', '/^[\!-\-\/-\~]*(\.[\!-\-\/-\~]+)+@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');

Becomes

define('regx_email', '/^[\!-\-\/-\~]*(\.[\!-\-\/-\~]+)*@(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z0-9]{2,6}$/');
0
 
LVL 15

Author Closing Comment

by:Insoftservice
ID: 39283739
Thanx
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 39283833
You are welcome - thanks for the points.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
What's wrong with this PDO query? 5 27
PHP error function not working on AWS 10 67
Email called spam 5 36
Wordpress Query 5 25
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question