Email Address Validation in PHP
One of the most common values that needs validation in PHP is the email address. You use this to signup for about 95% of websites. Email address validation isn’t necessarily difficult but if you’re unfamiliar with regular expressions and aren’t currently using a pre-built validation class or some other type of validation library, it can be tricky.
I’m here to solve all of that for you with a simple function, check it out:
function is_valid_email ($address) {
return (preg_match(
'/^[-!#$%&'*+\./0-9=?A-Z^_`{|}~]+'.
'@'.
'([-0-9A-Z]+.)+' .
'([0-9A-Z]){2,4}$/i',
trim($address)));
}
Using the email address validation function
/**
* Check if this email address validates
*/
if (is_valid_email($_REQUEST['email_address_here'])) {
/**
* It's a valid email address!
*/
} else {
/**
* It's an invalid email address!
*/
}
It’s as simple as that! I’ve tested it with a lot of email addresses thus far, so if you find any it can’t validate let me know.
Stuff that’s easy should be easier than stuff that’s easier than it.
Bryan
