Form Validations

Using regular expressions we can easily check if the information entered into particular fields is in a valid format. Here are a few common form field validations performed with a single PHP if statement.

Note that each preg_match() == 0 statement should be coded all on one line and you can replace the echo statement with whatever processing you want performed if the field is not valid. For optional fields simply add a test for the field being not equal to an empty string to the start of the if statement (eg. if ($phone != "" && preg_match(... ).

Phone Number

We can check a phone number (let's assume it is in a field called $phone) to make sure that it is a correctly formatted local or international phone number.


if (preg_match('/^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/', $phone) == 0)
  echo "$phone is not in a valid phone number format";

Examples of valid values: '+61 2 9555 1234' and '123-555-1234 x5678'

Email Address

This will validate the more common of the three email address formats (for $email).


if (preg_match('/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/' , $email) == 0)
  echo "$email is not in a valid email address";

Note that the expression should be all on one line, I have split it here simply so it fits on the page.

Examples of valid values: 'joe@example.com.au' and 'bill.baker@big-site.museum'

Date

This will validate that a date has been correctly entered in a numeric day month year order (international format) with a year between 1900 and 2099 (for $date).


if (preg_match('/^(0?[1-9]|[12][0-9]|3[01])[\/\.- ](0?[1-9]|1[0-2])[\/\.- ](19|20)\d{2}$/', $date) == 0)
  echo "$date is not in a valid numeric day month year fdormat";

Examples of valid values: '28/1/2006' and '19-07-1965'

Here's the corresponding code for numeric month day year (American Format).


if (preg_match('/^(0?[1-9]|1[0-2])[\/\.- ](0?[1-9]|[12][0-9]|3[01])[\/\.- ](19|20)\d{2}$/', $date) == 0)
  echo "$date is not in a valid numeric month day year format";

Examples of valid values: '01-28-2006' and '7 19 1965'

And finally, the corresponding code for numeric year month day (Japanese format).


if (preg_match('/^(19|20)\d{2}[\/\.- ](0?[1-9]|1[0-2])[\/\.- ](0?[1-9]|[12][0-9]|3[01])$/', $date) == 0)
  echo "$date is not in a valid numeric year month day format";

Examples of valid values: '2006-01-28' and '1965/7/19'

This one will accept dates in either international or Japanese format.


if (preg_match('/^((0?[1-9]|[12][0-9]|3[01])[\/\.- ](0?[1-9]|1[0-2])[\/\.- ](19|20)\d{2})|((19|20)\d{2}[\/\.- ](0?[1-9]|1[0-2])[\/\.- ](0?[1-9]|[12][0-9]|3[01]))$/', $date) == 0)
  echo "$date is not in a valid numeric day month year or year month day format";

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate