技术开发 频道

PHP开发经典教程:垃圾处理

回到课堂 

    既然你掌握了输入验证的基本部分,那么你应该清楚这是一项你将会经常执行的任务。因此创建一个可重用的用于输入验证的函数库就变得有意义了,你可以在一个应用程序每次需要其输入被检查以发现错误时使用该函数库。那就是我下一步将要做的事情(创建一个PHP类,该类展示出用于数据验证和错误处理的基本的对象方法,然后使用该类验证一个表单)。 

    下面是类的定义class.formValidator.php,它是为PHP 5编写的。你只需去除类方法的public和private标记然后使得私有的errorList属性作为一个变量就可以使其适合PHP 4。下列脚本的其余部分可运行于任意PHP版本下。
<?php // PHP 5 // class definition // class encapsulating data validation functions class formValidator { // define properties private $_errorList; // define methods // constructor public function __construct() { $this->resetErrorList(); } // initialize error list private function resetErrorList() { $this->_errorList = array(); } // check whether input is empty public function isEmpty($value) { return (!isset($value) || trim($value) == '') ? true : false; } // check whether input is a string public function isString($value) { return is_string($value); } // check whether input is a number public function isNumber($value) { return is_numeric($value); } // check whether input is an integer public function isInteger($value) { return (intval($value) == $value) ? true : false; } // check whether input is alphabetic public function isAlpha($value) { return preg_match('/^[a-zA-Z]+$/', $value); } // check whether input is within a numeric range public function isWithinRange($value, $min, $max) { return (is_numeric($value) && $value >= $min && $value <= $max) ? true : false; } // check whether input is a valid email address public function isEmailAddress($value) { return eregi('^([a-z0-9])+([\.a-z0-9_-])*@([a-z0-9_-])+(\.[a-z0-9_-]+)*\.([a-z]{2,6})$', $value); } // check if a value exists in an array public function isInArray($array, $value) { return in_array($value, $array); } // add an error to the error list public function addError($field, $message) { $this->_errorList[] = array('field' => $field, 'message' => $message); } // check if errors exist in the error list public function isError() { return (sizeof($this->_errorList) > 0) ? true : false; } // return the error list to the caller public function getErrorList() { return $this->_errorList; } // destructor // de-initialize error list public function __destruct() { unset($this->_errorList); } // end class definition } ?>
    剥离该脚本的其他部分只剩其本质部分,该formValidator类包含两个主要的组成部分。
 
    第一个是接受待验证的数据的一系列的方法,测试该数据以确定其是否有效(然而,“有效性”可以定义于方法内部)然后返回一个布尔结果代码。下面是被支持的方法列表:

• isEmpty() –测试一个值是否为空字符串
• isString() –测试一个值是否是字符串
• isNumber()-测试一个值是否是数值型字符串
• isInteger()-测试一个值是否为整数
• isAlpha() –测试一个值是否只由字母字符组成
• isEmailAddress()-测试一个值是否是一个电子邮件地址
• isWithinRange()- 测试一个值是否落在一个数值范围内
• isInArray()-测试一个值是否存在于一个数组中。 

    很明显地,上述列表是不完全的(你应该按照你自己的要求自由对其进行添加)。 

    在本教程更早之前的例子中,我做了一些事情以使得当遇到输入错误时,数据验证程序将会以die()函数立即结束脚本的处理。在真实世界里,在第一次错误发生时如此突然的程序终止通常情况下不是一个好主意;相反,处理所有的用户输入,识别所有的错误然后为了用户立即修正这些错误将其列示出来会更加有效。 

    那就是该类的第二个组成部分所出现的地方。它是一个持有在验证过程中遇到的所有错误的列表的PHP数组和操作该结构的一些方法。下面是方法的列表:

• isError()-检查是否任何错误存在于错误列表中
• addError()-向错误列表中增加一个错误
• getErrorList()-取得当前的错误列表
• resetErrorList()-重置错误列表 

    此刻,这个对你来说看上去有些深奥。让我们跳入一个实际的例子然后所有的上述代码将会开始变得更加有意义。首先,我们需要一个简单的HTML表单:
<html> <head></head> <body> <b>Fields marked with * are mandatory</b> <form action = 'processor.php' method = 'post'> <b>Name*:</b> <br /> <input type = 'text' name = 'name' size = '15'> <p /> <b>Age*:</b> <br /> <input type = 'text' name = 'age' size = '2' maxlength = '2'> <p /> <b>Email address*:</b> <br /> <input type = 'text' name = 'email' size = '30'> <p /> <b>Sex*:</b> <br /> <input type = 'radio' name = 'sex' value = 'm'>Male <input type = 'radio' name = 'sex' value = 'f'>Female <p /> <b>Color*:</b> <br /> <select name = 'color'> <option value = ''>-select one-</option> <option value = 'r'>Red</option> <option value = 'g'>Green</option> <option value = 'b'>Blue</option> <option value = 's'>Silver</option> </select> <p /> <b>Insurance*:</b> <br /> <select name = 'insurance'> <option value = ''>-select one-</option> <option value = '1'>Basic</option> <option value = '2'>Enhanced</option> <option value = '3'>Premium</option> </select> <p /> <b>Optional features:</b> <br /> <input type = 'checkbox' name = 'options[]' value = 'PSTR'>Power steering <input type = 'checkbox' name = 'options[]' value = 'AC'>Air-conditioning <input type = 'checkbox' name = 'options[]' value = '4WD'>Four-wheel drive <input type = 'checkbox' name = 'options[]' value = 'SR'>Sun roof <input type = 'checkbox' name = 'options[]' value = 'LUP'>Leather upholstery <p /> <input type = 'submit' name = 'submit' value = 'Save'> </form> </body> </html>
现在,我们需要一个使用我新的formValidator对象的PHP脚本来处理通过该表单发送的输入。将下列代码保存为processor.ph:
<?php // include file containing class include('class.formValidator.php'); // instantiate object $fv = new formValidator(); // start checking the data // check name if ($fv->isEmpty($_POST['name'])) { $fv->addError('Name', 'Please enter your name'); } // check age and age range if (!$fv->isNumber($_POST['age'])) { $fv->addError('Age', 'Please enter your age'); } else if (!$fv->isWithinRange($_POST['age'], 1, 99)) { $fv->addError('Age', 'Please enter an age value in the numeric range 1-99'); } // check sex if (!isset($_POST['sex'])) { $fv->addError('Sex', 'Please select your gender'); } // check email address if (!$fv->isEmailAddress($_POST['email'])) { $fv->addError('Email address', 'Please enter a valid email address'); } // check color if ($fv->isEmpty($_POST['color'])) { $fv->addError('Color', 'Please select one of the listed colors'); } // check insurance type if ($fv->isEmpty($_POST['insurance'])) { $fv->addError('Insurance', 'Please select one of the listed insurance types'); } // check optional features if (isset($_POST['options'])) { if ($fv->isInArray($_POST['options'], '4WD') && !$fv->isInArray($_POST['options'], 'PSTR')) { $fv->addError('Optional features', 'Please also select Power Steering if you would like Four-Wheel Drive'); } } // check to see if any errors were generated if ($fv->isError()) { // print errors echo '<b>The operation could not be performed because one or more error(s) occurred.</b> <p /> Please resubmit the form after making the following changes:'; echo '<ul>'; foreach ($fv->getErrorList() as $e) { echo '<li>'.$e['field'].': '.$e['message']; } echo '</ul>'; } else { // do something useful with the data echo 'Data OK'; } ?>
    正如上述列表所说明的,我的formValidator()对象所展示的各种方法很容易验证用户的输入。在所有情况下,isEmpty()方法用于测试必需的字段是否已经被填写了,而isEmailAddress()和isWithinRange()方法用于更精确的验证。isInArray()方法(对检查框和多选列表非常有用)也是一种强制关联规则和连接特定选择的好方法。
 
    注意到上述所创建的formValidator类与表单或者表单的结果页面的可视化展现无关是重要的。它的方法仅仅测试发送给他们的输入然后返回结果码;结果码是如何被解释的完全取决于开发人员。在上面脚本中,foreach()循环对错误列表进行循环操作然后以无序列表的形式对其进行打印;然而,你可以以定制格式的方式在表格中显示错误信息或者将其写入到日志文件中。我将任你去实验这种可能性。 

    那就是PHP 101中本部分的内容。但是,别沮丧,我将很快回来而且下次,我将拾起我所交给你的一切然后使用他们来构建一个真实世界中的PHP/MySQLWeb应用。确保你不会错过那个!
0
相关文章