[英]Error with the Validation Code
我的驗證類中有以下驗證方法:
public function validate($data, $rules)
{
if(!is_array($rules))
{
$rules = array($rules);
}
foreach($rules as $rule)
{
if(is_array($rule))
{
if(!$this->{$rule[0]}($data, $rule[1]))
{
array_push($this->errors, $rule[0] . ' is ' . $rule[1]);
$ruleValue = $rule[0];
print_r($this->errorMessages[$ruleValue] . BR);
return $this->errors;
}
}
else
{
if(!$this->{$rule}($data))
{
array_push($this->errors, $rule);
print_r($this->errorMessages[$rule] . BR);
return $this->errors;
}
}
}
if(empty($this->errors))
{
return TRUE;
}
}
使用檢查有效日期的方法(即小於當前日期)
private function validDate($data)
{
$now = date('Ymd');
return ($data < $now) ? TRUE : FALSE;
}
我有另一個php文件創建此Validation類,然后檢查輸入並驗證它:
if
(
$Validation->validate($email, array('required', 'isEmail')) &&
$Validation->validate($password, array('required', array('min_length', '6'), array('max_length', '20'))) &&
$Validation->validate($repeatPassword, array('required', array('min_length', '6'), array('max_length', '20'), array('matches', Input::fetch('password')))) &&
$Validation->validate($date, array('required', 'validDate'))
)
{
echo 'Yes';
}
現在,理想情況下,當所有驗證都為真時,應該執行echo代碼,並且在我更改Validation類中的有效Date方法之前它已正常工作。
它打印錯誤,這意味着它返回false,但也回顯了消息“是”。
我在if
語句中使用了&&
,這意味着如果任何一個條件為false,代碼將不會被執行但我似乎無法理解為什么它在所有條件都返回false時運行。
你回來了
return $this->errors;
在您的驗證功能中。 但它的定義不是假或0,所以它是真的 ,它通過你的條件。 你應該回歸虛假
方法validate
總是返回不同的false,因此if
表達式始終為true。 這樣,您將獲得錯誤,並且還會顯示“是”輸出。 我建議你根據驗證使方法返回true或false,並將錯誤設置為公共屬性,這樣你就可以在錯誤驗證的情況下讀取它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.