Commonly Used Regular Expressions

Here is a function that I have developed in PHP for checking to see if data is in a valid format. These are some of the common validations I have needed while programming various projects and websites. Regular expressions are some of the most powerful validation checks available in PHP, however they are not always easy to understand.

This function is used by passing 2 arguments: the type of validation check you want to be performed, and the data you want validated. The function itself uses a simple switch statement (a quicker and cleaner if/then statement). The function simply returns a boolean True or False.


function isValid($type,$var) {
$valid = false;
switch ($type) {
case "IP":
if (ereg("^([0-9]{1,3}\.){3}[0-9]{1,3}$",$var)) {
$valid = true;
}
break;
case "Email":
if (ereg("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$",$var)) {
$valid = true;
}
break;
case "URL":
if (ereg("^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu)$",$var)) {
$valid = true;
}
break;
case "SSN":
if (ereg("^[0-9]{3}[- ][0-9]{2}[- ][0-9]{4}|[0-9]{9}$",$var)) {
$valid = true;
}
break;
case "CC":
if (ereg("^([0-9]{4}[- ]){3}[0-9]{4}|[0-9]{16}$",$var)) {
$valid = true;
}
break;
case "ISBN":
if (ereg("^[0-9]{9}[[0-9]|X|x]$",$var)) {
$valid = true;
}
break;
case "Date":
if (ereg("^([0-9][0-2]|[0-9])\/([0-2][0-9]|3[01]|[0-9])\/[0-9]{4}|([0-9][0-2]|[0-9])-([0-2][0-9]|3[01]|[0-9])-[0-9]{4}$",$var)) {
$valid = true;
}
break;
case "Zip":
if (ereg("^[0-9]{5}(-[0-9]{4})?$",$var)) {
$valid = true;
}
break;
case "Phone":
if (ereg("^((\([0-9]{3}\) ?)|([0-9]{3}-))?[0-9]{3}-[0-9]{4}$",$var)) {
$valid = true;
}
break;
case "HexColor":
if (ereg("^#?([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?$",$var)) {
$valid = true;
}
break;
case "User":
if (ereg("^[a-zA-Z0-9_]{3,16}$",$var)) {
$valid = true;
}
break;
}
return $valid;
}

Example:

$email_address = $_POST["email"];
if (isValid("Email",$email_address)) {
echo "Valid Email Address;
} else {
echo "Invalid Email Address;
}

For more information, help, and examples visit RegExLib.com or check out the Mastering Regular Expressions book.