How to Validate URLs and E-Mail Addresses in Web Form Fields - dummies

How to Validate URLs and E-Mail Addresses in Web Form Fields

By Steve Suehring, Janet Valade

Truly validating an e-mail address in a web form field is a surprisingly difficult task. The standard for e-mail addresses allows for complex combinations of letters, numbers, and special characters, some of which can only appear in certain positions. PHP versions 5.2 and greater include a filter_var() function that takes this complexity away and makes it easier to filter things like e-mail addresses and URLs (among other things).

Validate an e-mail address

The filter_var() function includes a number of built-in tests to check to see if an e-mail address is valid.

Select Validation Filters in PHP
Filter Description
FILTER_VALIDATE_BOOLEAN Validates that a value is a Boolean.
FILTER_VALIDATE_INT Validates that a number is an integer.
FILTER_VALIDATE_FLOAT Validates that a number is a floating point number.
FILTER_VALIDATE_IP Validates an IP address.
FILTER_VALIDATE_EMAIL Validates an e-mail address.

Using the filters is very easy. For example, here’s the code to validate an e-mail address. This code could be plugged into the form-process.php file above the final disposition section:

if (!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL)) {
    $_SESSION['error'][] = "Invalid e-mail address";

That code is all you need to validate an e-mail address in PHP.

Validate a URL

URLs can be validated in the same way. Say you have a variable called $url. The validation code looks the same; it just uses a different filter.

if (!filter_var($url,FILTER_VALIDATE_URL)) {
    $_SESSION['error'][] = "Invalid URL";