Link to home
Start Free TrialLog in
Avatar of Insoftservice inso
Insoftservice insoFlag for India

asked on

php email validation for subdomain

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
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

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}$/');
Avatar of Insoftservice inso

ASKER

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)
Tried your code replacing my regex pattern but it failed
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

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
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

@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
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
@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.
@insoftservice - did you see my last post - how did my suggestion fail on your side?
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:
https://www.experts-exchange.com/questions/28140356/php-email-validation-for-subdomain.html?anchorAnswerId=39201286#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().

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.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanx
You are welcome - thanks for the points.