復制代碼 代碼如下: <?php /** * Validator for Register. */ final class RegisterValidator { private function __construct() {
} /** * Validate the given username, password, repeat_password and email. * @param $username, $password, $repeat_password and $email to be validated * @return array array of {@link Error} s */ public static function validate($username, $password, $repeat_password, $email) { $errors = array(); $username = trim($username); $password = trim($password); if (!$username) { $errors[] = new Error('username', '用戶名不能為空。'); } elseif (strlen($username)<3) { $errors[] = new Error('username', '用戶名長度不能小于3個字符。'); } elseif (strlen($username)>30) { $errors[] = new Error('username', '用戶名長度不能超過30個字符。'); } elseif (!preg_match('/^[A-Za-z]+$/',substr($username, 0, 1))) { $errors[] = new Error('username', '用戶名必須以字母開頭。'); } elseif (!preg_match('/^[A-Za-z0-9_]+$/', $username)) { $errors[] = new Error('username', '用戶名只能是字母、數字以及下劃線( _ )的組合。'); } elseif (!$password) { $errors[] = new Error('password', '密碼不能為空。'); } elseif (strlen($password)<6) { $errors[] = new Error('password', '密碼長度不能小于6個字符。'); } elseif (strlen($password)>30) { $errors[] = new Error('password', '密碼長度不能超過30個字符。'); } elseif (!preg_match('/^[A-Za-z0-9!@#//$%//^&//*_]+$/', $password)) { $errors[] = new Error('password', '密碼只能是數字、字母或!@#$%^&*_等字符的組合。'); } elseif ($password != trim($repeat_password)) { $errors[] = new Error('password', '兩次輸入密碼不一致。'); } elseif (!Utils::isValidEmail($email)) { $errors[] = new Error('email', '郵箱格式有誤。'); } else { // check whether user exists or not $dao = new UserDao(); $user = $dao->findByName(trim($username)); if ($user) { $errors[] = new Error('username', '該用戶名已經被使用。'); }
$user = null; // check whether email being used or not $user = $dao->findByEmail(trim($email)); if ($user) { $errors[] = new Error('email', '該郵箱已被注冊。'); } } return $errors; } } ?>