To check if a URL or an email address is valid, the common solution is regular expressions. For instance, to validate an email address in PHP, I would use:
if (preg_match('|^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|i', $email)) {
// $email is valid
}
A simpler and more forgiving one would be:
|^\S+@\S+\.\S+$|
Which is usually quite enough for signup forms in preventing stupid typo errors. You get to validate the email by a validation link sent to the address anyway, as a final call whether the address is valid or not. For those who are obsessively curious, this may serve you well.
For URL, you can use this one:
|^\S+://\S+\.\S+.+$|
Or you can use one that is insanely detailed in addressing what a valid URL should be.
The filter_var() function of PHP5
What we are talking about here really is the filter_var() function of PHP5 that simplifies the URL and email validation by a large degree. To validate an email:
if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) {
// $email contains a valid email
}
To validate a URL:
if (filter_var($url, FILTER_VALIDATE_URL) !== false) {
// $url contains a valid URL
}
While filter_var() is meant to return the filtered results of the input according to the filter type specified, such as FILTER_VALIDATE_EMAIL or FILTER_VALIDATE_URL, you can generally use it to see if a valid email or a valid URL can be extracted from something. Better yet, filter and get the results first, use the result if it is good or abandon it when it is false:
$filtered_email = filter_var($email, FILTER_VALIDATE_EMAIL);
if ($filtered_email !== false) {
// $filtered_email is the valid email got out of $email
} else {
// nothing valid can be found in $email
}
Same applies to FILTER_VALIDATE_URL. Here’s a full list of filter types of filter_var() you can take advantage of.
You should also read:
- Regular Expression for Date and Time Strings
- PHP: How to detect / get the real client IP address of website visitors?
- PHP: Check if a string contains another string or substring
- PHP: Allow Specific HTML Tags in Text Input Controls of HTML Forms, <textarea>, <input type=”text” />
- How to get all the sub-directories of a given directory in PHP?


Facebook
Twitter
Google Plus
{ 3 comments… read them below or add one }
This is a nice example. Its easy to understand..
doing a good job.
Thanks a lot..!
I love the filter_var function for validation, EXCEPT for this one fact:
The FILTER_VALIDATE_URL filter has a bug in it that fails url hostnames with hyphens in them, as of 5.2.13. That sucks!
if (filter_var($url, FILTER_VALIDATE_URL) !== false)
==> if (filter_var($url, FILTER_VALIDATE_URL))
it’s the same !!!!
and more understandable
{ 1 trackback }