1

I am currently SwiftMailer to send out emails. I have a seperate email validation script that checks emails to ensure they are valid before using SwiftMailer to send. It works pretty well.

However, my validator doesn't pick up accidental double dots (..) in email addresses like:

ben..sinclair@email.com OR ben.sinclair@email..com

Here's my code... what would I need to add in to give an error if they put double dots anywhere in the email address?

function valid_email($email) {
    if (preg_match("/[_a-z0-9-]+(\.[_a-z0-9-]+)*@([_0-9a-z][_0-9a-z-]*[_0-9a-z]\.)+[0-9a-z][a-z]+/", $email, $matches))
        return true;
    return false;
}
Ben Sinclair
  • 3,896
  • 7
  • 54
  • 94

1 Answers1

1

answer to filter_var suggestion: FILTER_VALIDATE_EMAIL validates with no tld, it is not perfect, it thinks name@example is a valid e-mail addr while it is not, for instance.

function checkEmailAddress( $email = "" ) {
    $email = trim($email);
    $email = str_replace( " ", "", $email );
    if( filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE )
        return FALSE;
    if ( substr_count( $email, '@' ) > 1 )//more than one '@'?
        return FALSE;
    if ( preg_match( "#[\;\#\n\r\*\'\"<>&\%\!\(\)\{\}\[\]\?\\/\s]#", $email ) )
        return FALSE;
    else if ( preg_match( "/^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,4})(\]?)$/", $email) )
        return TRUE;
    else
        return FALSE;
}

hope it helps :)

Canneh
  • 50
  • 5
  • Didn't even know about FILTER_VALIDATE_EMAIL! That's awesome, good call on checking several times to ensure it works. You rock! – Ben Sinclair Nov 17 '11 at 03:06
  • Also, any clue on stopping double dots? You code doesn't seem to pick it up either... – Ben Sinclair Nov 17 '11 at 03:08
  • "name@example " is valid, but can be only used in internal network websites, that's why FILTER_VALIDATE_EMAIL allow it. If you're coding a public website then you should do additional validations. See this answer and comments: http://stackoverflow.com/a/20573804 Also more than one @ and unicode characters are also valid, it just depends if your email server supports those. Gmail, as an example, support it. – Gustavo Rodrigues Jun 15 '16 at 13:34