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(... ).
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.
Examples of valid values: '+61 2 9555 1234' and '123-555-1234 x5678'
This will validate the more common of the three email address formats (for $email).
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: 'email@example.com' and 'firstname.lastname@example.org'
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).
Examples of valid values: '28/1/2006' and '19-07-1965'
Here's the corresponding code for numeric month day year (American Format).
Examples of valid values: '01-28-2006' and '7 19 1965'
And finally, the corresponding code for numeric year month day (Japanese format).
Examples of valid values: '2006-01-28' and '1965/7/19'
This one will accept dates in either international or Japanese format.
This article written by Stephen Chapman, Felgall Pty Ltd.