A very common need in PHP-based Web applications is to validate email addresses. An email address, at its most basic contains the @ and a dot and no spaces or special characters, so it’s pretty easy coming up with a regular expression that will fit this most simple restriction. However, if you want a full-on precise regular expression, that takes an immense amount of code (the full email validation pattern takes up almost a page of code). An alternative, then is to use the EmailAddressValidation class, created by Added Bytes and now hosted on Google Code.
After you’ve downloaded the code and put it on your server, you use it like so:
require('/path/to/EmailAddressValidator.php');
$emailValidator = new EmailAddressValidator();
if ($emailValidator->check_email_address('test@example.org')) {
// Email address is technically valid.
} else {
// Email not valid.
}
Why not using built-in filters?
if(filter_var(‘test@example.org’, FILTER_VALIDATE_EMAIL){
// Email address is technically valid.
}
else {
// Email not valid.
}
Thanks for your post. Yes, PHP’s built-in filters are a great option and one I write about in my PHP 5 Advanced book (I think), but these functions are only available (by default) as of PHP 5.2, which not everyone, particularly on shared hosts, have available at the moment. Still, definitely worth considering. Thanks again!
You definitely do cover the filter functions in your PHP 5 Advanced book Larry. Also covered is the PEAR Auth package.
What percentage of coding do you think data validation takes up? I reckon writing computer programs is easy, writing programs for humans on the other hand is validation, validation, validation!
Thanks for confirming that, Jason. It’s tragic that I can barely remember what I’ve actually written!
As for percentage of coding, the answer is somewhere between “so much” and “too much”. In fact I’m just wrapping a moderately complex site that I developed using the Yii framework and I spent some time wondering if a framework was a good choice. Mostly because I’d go to do X and then need to look through all the docs to figure out how to do X using Yii. But when I think about how much effort goes into simple validation and error reporting, I think the framework’s a good choice. There’s great peace of mind knowing that this value will be empty or an integer, nothing else, and that this will be a valid email address, in every situation: creating new record, updating them, etc. So many conditionals required to pull this off properly without using a framework or other tool!