Solved

Email Validation

Posted on 2010-09-21
8
781 Views
Last Modified: 2013-12-26
Hi,

I need some help with improving an email validation script, any input will be highly appreciated. Thank you.

#!/usr/bin/perl
use Data::Dumper;

%lookup_cache = ();

sub valid_address {
  my($addr) = @_;
  my($domain, $valid);

  # Lower-case address
  $addr = lc($addr);

  # Validate format of address
  return(0) unless ($addr =~ /^[^@]+@([-\w]+\.)+[a-z]{2,4}$/);

  # Grab domain
  $domain = (split(/@/, $addr))[1];

  # Lookup and return cached result if it exists
  $cached_result = $lookup_cache{$domain};
  if ($cached_result ne '')
  {
    print "[cached_result] ";
    return $cached_result;
  }

  # Do domain lookup
  $valid = 0;
  if (open(DNS, "nslookup -q=any $domain |"))
  {
    while (<DNS>) {
      $valid = 1 if (/^$domain.*\s(mail exchanger|internet address)\s=/i);
    }
  }

  # Store cached result for later
  $lookup_cache{$domain} = $valid;

  return $valid;
}

while (<>) {
  $addy = $_;
  $addy =~ s/\s+$//;
  if ($addy)
  {
    print "$addy " . (valid_address($addy) ? 'valid' : 'invalid') . "\n";
  }
}
0
Comment
Question by:faithless1
8 Comments
 
LVL 12

Expert Comment

by:Rant32
ID: 33723610
Perl has a module for that: Email::Valid

http://search.cpan.org/~rjbs/Email-Valid-0.184/lib/Email/Valid.pm

Hope this helps.
0
 
LVL 3

Expert Comment

by:Progressed
ID: 33723923
jquery has that build in... you could take a look at:

http://flowplayer.org/tools/demos/index.html

You can download a prepacked JS with builtin Jquery. its much easier!
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 33725110
This function has always served me well.  HTH, ~Ray
<?php // RAY_temp_email_validation.php

error_reporting(E_ALL);







// A FUNCTION TO TEST FOR A VALID EMAIL ADDRESS, RETURN TRUE OR FALSE

function check_valid_email($email)

{

    // IF PHP 5.2 OR ABOVE, WE CAN USE THE FILTER

    // MAN PAGE: http://us3.php.net/manual/en/intro.filter.php

    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

        ;

        if (!preg_match($regex, $email)) return FALSE;

    }



    // FILTER or PREG DOES NOT TEST IF THE DOMAIN OF THE EMAIL ADDRESS IS ROUTABLE

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

    if ( checkdnsrr($domain[1],"MX") || checkdnsrr($domain[1],"A") ) return TRUE;



    // EMAIL NOT ROUTABLE

    return FALSE;

}









// DEMONSTRATE THE FUNCTION IN ACTION

$e = '';

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 PHP - PUT UP THE FORM

?>

<form method="get">

TEST A STRING FOR A VALID EMAIL ADDRESS:

<input name="e" value="<?php echo $e; ?>" />

<input type="submit" />

</form>

Open in new window

0
 
LVL 25

Expert Comment

by:madunix
ID: 33725183
Validate an E-Mail Address with PHP, the Right Way...
look @ http://www.linuxjournal.com/article/9585
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33725343
A quote from the comments on http://www.linuxjournal.com/article/9585 (PHP has changed a bit since 2007, eh?)

"I can't believe LJ have allowed this article to remain here uncorrected for so long."

That is why I test my code before posting it here.  The code snippet at 33725110 is fully functional and self-contained.  You can install it and run it to see the moving parts.

best to all, ~Ray
0
 
LVL 1

Expert Comment

by:ahmad_alinat
ID: 33736265
php has its built in function to validate email:
http://php.net/manual/en/function.filter-var.php
<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('example.com', FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED));
?>

Open in new window

0
 

Author Comment

by:faithless1
ID: 33762899
Ray, can you please include command line usage? I have a txt file that i'm looking to enter as input.thanks.
0
 
LVL 12

Expert Comment

by:Rant32
ID: 33763703
I don't know if filter_var is any better, but trying to validate email addresses with regex is an excercise in futility. Those expressions would lock out my.address+EE.com@gmail.com and hostmaster@com ...

Those are perfectly valid email addresses, you know... Especially the '+' character... You have any idea how annoying it is to have some web form tell you you can't use it, even if it's perfectly valid (everything after + should be ignored for the local part).

You. Can't. Catch. RFC5322. In a regular expression.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Utilizing an array to gracefully append to a list of EmailAddresses
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

947 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now