Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Validate an email address with PHP

Wednesday, September 26th, 2012 by Servage

I’ve seen the weirdest things among website developers, on how they try to validate an email address. Everything from highly complex if/else combinations to impossible regular expressions. However, it’s really easy to validate an email address with PHP, because there is a built-in function. Why do so many people not know that? So… I say it once more: There is a built in function to validate email addresses in PHP :-)

$email = "someone@exa mple.com";

if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo "E-mail is not valid";
}
else {
  echo "E-mail is valid";
}

You can even put it inside a functions or an object method. I have attached it as an object method in the example below:

$email = "someone@exa mple.com";

class Person {
  var $email;
  function setEmail($email) {
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $this->email = $email;
      return true;
  }
  else {
    return false;
  }

$person = new Person;
if ($person->setEmail('test@me.com'))
  echo 'Valid email set';
else
  echo 'Invalid email. Not set.';

It’s as easy as that to validate email addresses in PHP. Read more about filters here.

Validate an email address with PHP, 5.0 out of 5 based on 5 ratings
Categories: Guides & Tutorials, Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.