Email validation with preg_match

Creator:
Virst
Description:
Learn how to find out if an email is valid.

We are going to use preg_match to validate an email. The pattern is:



<?php 
    $pattern 
"#^([a-z0-9-_]+)(.[a-z0-9-_]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*.[a-z]{2,4}$#i""; 
?> 

Here is how you validate it:


<?php 
    $pattern 
"#^([a-z0-9-_]+)(.[a-z0-9-_]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*.[a-z]{2,4}$#i"
    
$email "someone@someplace.com"
        if(
preg_match($pattern$email)){ 
            echo 
"Email is valid."
        }else{ echo 
"Email is invalid."; } 
?>

PHP will print out "Email is valid" if the email is valid.

Here is a useful function to validate emails:



<?php 
    
function is_valid_email($email){ 
        if(
preg_match("#^([a-z0-9-_]+)(.[a-z0-9-_]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*.[a-z]{2,4}$#i",$email)){ 
            return 
true
        }else{ 
            return 
false; }
    } 
?> 

Here is how you can use the function:


<?php 
    
if(is_valid_email("someone@someplace.com")){ 
        echo 
"email is valid!"
        }else{ 
            echo 
"not valid"; } 
?>

Comments

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <b> <u> <i> <hr> <img src <url=
  • Lines and paragraphs break automatically.

More information about formatting options