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.
No comments yet (leave a comment)