UltraMega Blog
31Mar/091

Easy Text Validation Without Regular Expressions

Filtering data from user input and other external sources is the most important part of writing secure code, but it's also handy to make sure users supply the correct type of info to a registration form for example. Sometimes it's simply making sure something is a number or of a certain length, but other times it's something that follows a specific pattern (like an email address). This used to be a job for complex regular expressions, but fortunately, there is an easier and more reliable solution.

PHP 5.2.0 and up comes with a very convenient set of data filtering functions. These functions allow you to easily validate common things such as emails and URLs, that would otherwise require complex regular expressions that don't always work. This tutorial will focus on the simplest function filter_var().

The filter_var function looks like this:

mixed filter_var ( mixed $variable [, int $filter= FILTER_DEFAULT [, mixed $options ]] )

  • $variable - Input value to validate
  • $filter - Filter ID to use for validation
  • $options - Option flags for filter, or callback functions for callback filter
  • Returns - Filtered data or FALSE if filter fails

For a complete reference of filter flags and options, see http://www.w3schools.com/php/php_ref_filter.asp

There are basically two types of filters you can use, "sanitize" and "validate" filters. Sanitize filters basically remove unwanted characters from a string so it is "safe" for certain uses. Validate filters are used just to check is the text is valid for the specified filter and returns FALSE if it is not. There is also a filter called FILTER_CALLBACK that allows you to create custom functions to run on the input text.

Here are some examples of usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// check if an email address is valid
$email = "someone@somewhere.com";
if(filter_var($email, FILTER_VALIDATE_EMAIL) !==  false) {
   echo "Email is valid!";
}
 
// check if URL is valid and includes scheme and host
// (note use of "|" character to use multiple flags)
$url = "http://example.com";
if(filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED) !== false) {
   echo "URL is valid!";
}
 
// remove unsafe characters from an email address
$email = "someone@s()ome;where.com";
echo filter_var($email, FILTER_SANITIZE_EMAIL); // outputs: someone@somewhere.com

As you can see, this is a very simple method of validation. For related functions, see the PHP manual.

Posted by Steve

Comments (1) Trackbacks (0)
  1. nice, thanks for sharing. I’m using regular expression and as a beginner that’s really difficult to understand 😀 this really saves me a lot of time


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

No trackbacks yet.