<?php
class Validator {
public $errors = array(
'password' => '',
'email' => '');
const PASSWORD_MINCHARS = 8;
public function checkEmail($email) {
if ($this->checkEmpty($email)) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->errors['email'] = "Please provide a valid email";
return FALSE;
} else {
return TRUE;
}
} else {
$this->errors['email'] = "Please provide a value for the email";
return FALSE;
}
}
public function checkPassword($string) {
if ($this->checkEmpty($string)) {
if (strlen($string) < self::PASSWORD_MINCHARS) {
$this->errors['password'] = "The password should be atleast ".self::PASSWORD_MINCHARS." characters long.";
return FALSE;
} else {
return TRUE;
}
} else {
$this->errors['password'] = "Please provide a value for the password";
return FALSE;
}
}
private function checkEmpty($string) {
if (!empty($string)) {
return TRUE;
}
return FALSE;
}
public function displayErrors() {
$output = '';
foreach ($this->errors as $error) {
if (!empty($error)) {
$output .= '<p>'.$error.'</p>';
}
}
return $output;
}
}
?>
<?php
require 'Validator.php';
$validator = new Validator();
$email = '';
$password = '';
if ($validator->checkPassword($password) && $validator->checkEmail($email)) {
echo 'You have entered a valid password and email.';
} else {
echo $validator->displayErrors();
}
?>
上面的代码来自两个单独的文件。从Validator.php开始的Validator来自Validator.php,而以require函数开头的那个来自index.php。所以我只是想知道为什么index.php中的$ validator-&gt; displayErrors()方法调用一次只显示一个错误,而不是一次显示所有错误。
答案 0 :(得分:0)
替换
if ($validator->checkPassword($password) && $validator->checkEmail($email))
与
if ($validator->checkPassword($password) || $validator->checkEmail($email)) {
答案 1 :(得分:0)
由于您的情况,只显示一个错误:
if ($validator->checkPassword($password) && $validator->checkEmail($email))
首先执行checkPassword方法,它返回false,因此永远不会检查第二个条件(应该执行第二个验证方法)。
您可以先通过执行验证方法来避免这种情况:
$validPassword = $validator->checkPassword($password);
$validEmail = $validator->checkEmail($email);
if ($validPassword && $validEmail) {
echo 'You have entered a valid password and email.';
} else {
echo $validator->displayErrors();
}