Using regular expressions to validate data

Regular expressions to test validity

Phone numbers as: 999-999-9999

/^[[:digit:]]{3}-[[:digit:]]{3}-[[:digit:]]{4}$/

Testing a phone number

$phone = '559-555-6624'; 
$phone_pattern = '/^[[:digit:]]{3}-[[:digit:]]{3}-[[:digit:]]{4}$/';
$match = preg_match($phone_pattern, $phone);  
// Returns 1

Credit card numbers as: 9999-9999-9999-9999

/^[[:digit:]]{4}(-[[:digit:]]{4}){3}$/

Zip codes as either: 99999 or 99999-9999

/^[[:digit:]]{5}(-[[:digit:]]{4})?$/

Dates as: mm/dd/yyyy

/^(0?[1-9]|1[0-2])\/(0?[1-9]|[12][[:digit:]]|3[01])\/[[:digit:]]{4}$ // on one line with no spaces

Tesing a date

$date = '8/10/209';         // invalid date
$date_pattern = '/^(0?[1-9]|1[0-2])\/' . '(0?[1-9]|[12][[:digit:]]|3[01])\/' . '[[:digit:]]{4}$/';
$match = preg_match($date_pattern, $date);    
// Returns 0

Back