从表单提交中处理数据验证的有效方法是什么?有效数据验证
最初我有一堆if
语句检查每个值并收集数组中的无效值以便以后检索(和列表)。
// Store errors here
$errors = array();
// Hypothetical check if a string is alphanumeric
if (!preg_match('/^[a-z\d]+$/i', $fieldvalue))
{
$errors[$fieldname] = 'Please only use letters and numbers for your street address';
}
// etc...
接下来我做了什么是创建一个类来处理各种数据验证场景并将结果存储在内部数组中。数据验证完成后我会检查,看看是否发生了任何错误,并进行相应处理:
class Validation
{
private $errorList = array();
public function isAlphaNumeric($string, $field, $msg = '')
{
if (!preg_match('/^[a-z\d]+$/i', $string))
{
$this->errorList[$field] = $msg;
}
}
// more methods here
public function creditCard($cardNumber, $field, $msg = '')
{
// Validate credit card number
}
// more methods here
public function hasErrors()
{
return count($this->errorList);
}
}
/* Client code */
$validate = new Validation();
$validate->isAlphaNumeric($fieldvalue1, $fieldname1, 'Please only use letters and numbers for your street address');
$validate->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number');
if ($validate->hasErrors())
{
// Handle as appropriate
}
自然,没多久之前,该类成为臃肿与几乎无限类型的数据进行验证。我现在正在做的是用装饰不同类型的数据到自己的类,需要留下的通用验证,只有当打电话给他们(即isAlphaNumeric())在基类:
class Validation
{
private $errorList = array();
public function isAlphaNumeric($string, $field, $msg = '')
{
if (!preg_match('/^[a-z\d]+$/i', $string))
{
$this->errorList[$field] = $msg;
}
}
// more generic methods here
public function setError($field, $msg = '')
{
$this->errorList[$field] = $msg;
}
public function hasErrors()
{
return count($this->errorList);
}
}
class ValidationCreditCard
{
protected $validate;
public function __construct(Validation $validate)
{
$this->validate = $validate;
}
public function creditCard($cardNumber, $field, $msg = '')
{
// Do validation
// ...
// if there is an error
$this->validate->setError($field, $msg);
}
// more methods here
}
/* Client code */
$validate = new Validation();
$validate->isAlphaNumeric($fieldvalue, $fieldname, 'Please only use letters and numbers for your street address');
$validateCC = new ValidationCreditCard($validate);
$validateCC->creditCard($fieldvalue2, $fieldname2, 'Please enter a valid credit card number');
if ($validate->hasErrors())
{
// Handle as appropriate
}
我是上正确的轨道?或者我只是把数据验证复杂化了,然后我需要呢?
我还使用了您在上描述的一样。我也有兴趣得到这个问题的答案。 Currenlty也是我验证一个表格。我使用TryParse和其他可能的inbuild函数。剩下我创造自己。 – 2010-05-17 11:53:03