從表單提交中處理數據驗證的有效方法是什麼?有效數據驗證
最初我有一堆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