All regular expressions are tested with php function eregi
Validate E-Mail
Username can contain letters, numbers, and dots
^([-a-z0-9._]{2,32}@([a-z0-9-]{1,64}[.]){1,5}([a-z0-9]){2,6}$|$)
Validate URL
Domain can contain letter, numbers and dashes. HTTP://, HTTPS:// and FILE:// allowed
^((http://|https://|file://){0,1}([a-z0-9-]{1,32}[.]){1,10}([a-z0-9]){2,3}(:[0-9]{1,5}){0,1}([/\]{1,3}[a-z0-9_-~.]{0,64}){0,16}([?][a-z0-9=%;+]+){0,1}$|$)
Example usage of url validation regular expression would go something like this (php):
if (!eregi("^((http://|https://|file://){0,1}" // type
.'([a-z0-9-]{1,32}[.]){1,10}([a-z0-9]){2,3}' // domain
.'(:[0-9]{1,5}){0,1}' // port
.'([/\]{1,3}[a-z0-9_-~.]{0,64}){0,16}' // directory
.'([?][a-z0-9=%;+]+){0,1}$|$)', // options
trim($url_to_validate))) echo "url not valid";
else echo "url is valid";
Validate Date/Time
Will check date/time in format ‘yyyy-m-d h:m:s’
^([0-9]{4})[-/.]([0-9]{1,2})[-/.]([0-9]{1,2}) ([0-9]{1,2})(:[0-9]{1,2})(:[0-9]{1,2}){0,1}$
To fully validate date/time input you might want to use something like this:
function datetimeValidation($datetime) {
if (eregi('^([0-9]{4})[-/.]([0-9]{1,2})[-/.]([0-9]{1,2}) ([0-9]{1,2})(:[0-9]{1,2})(:[0-9]{1,2}){0,1}$', trim($datetime), $t))
if (checkdate($t[2], $t[3], $t[1]))
if (($t[4] < 24)&&($t[5] < 60)&&($t[6] < 60))
return sprintf('%04d-%02d-%02d %02d:%02d:%02d', $t[1], $t[2], $t[3], $t[4], $t[5], $t[6]);
return false;
}
February 20th, 2008 at 11:18 am
thx
August 2nd, 2008 at 8:57 pm
FYI – ereg() is depreciated in PHP6. It would be wise to rework with preg, to keep it forward compatible.
I know that is just for an example, and the regular expressions are really the point of the post, I just wanted to point that out.