Building An Extensible Form Validator Class - Mail Dot Com
(Page 8 of 12 )
It's also possible to create more complex validation routines using PHP's built-in support for regular expressions. This next method, isAlpha(), uses a regular expression to test whether all the characters in the input string are alphabetic.
<?php
class FormValidator
{
// snip
// check whether input is alphabetic
function isAlpha($field, $msg)
{
$value = $this->_getValue($field);
$pattern = "/^[a-zA-Z]+$/";
if(preg_match($pattern, $value))
{
return true;
}
else
{
$this->_errorList[] = array("field" => $field,
"value" => $value, "msg" => $msg);
return false;
}
}
}
?>
This ability to use regular expressions to perform data
validation comes in particularly handy when checking user-supplied email addresses for validity - as the very cool (and very useful) class method isEmailAddress() demonstrates:
<?php
class FormValidator
{
// snip
// check whether input is a valid email address
function isEmailAddress($field, $msg)
{
$value = $this->_getValue($field);
$pattern =
"/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/
";
if(preg_match($pattern, $value))
{
return true;
}
else
{
$this->_errorList[] = array("field" => $field,
"value" => $value, "msg" => $msg);
return false;
}
}
}
?>
Next: Under Construction >>
More PHP Articles
More By icarus, (c) Melonfire