[英]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.