namespace app\models;
use Yii;
use yii\base\Model;
class RegisterForm extends Model
{
public $email;public $password;public $password_repeat;
public function rules(){ return [ [['email', 'password', 'password_repeat'], 'required'], ['email', 'email'], //['email', 'unique', 'targetClass' => '', 'message' => '郵箱名已存在。'], [['password', 'password_repeat'], 'string', 'length' => [6, 20]], ['password', 'checkPassword'], ['password_repeat','compare','compareAttribute' =>'password','message'=>'兩次輸入的密碼不一致。'], ];}public function register(){ //處理一些東西 //註冊相關的 return false;}public function attributeLabels(){ return [ 'email' => '郵箱', 'password' => '密碼', 'password_repeat' => '重複密碼', ];}public function checkPassword($attribute, $params){ if (!ctype_alnum($this->$attribute)) { $this->addError($attribute, '必須包含字母或數字。'); }}
}
checkPassword 這個獨立驗證器 使用不了 我代碼書寫有問題嗎 各位大哥們
回複內容:
namespace app\models;
use Yii;
use yii\base\Model;
class RegisterForm extends Model
{
public $email;public $password;public $password_repeat;
public function rules(){ return [ [['email', 'password', 'password_repeat'], 'required'], ['email', 'email'], //['email', 'unique', 'targetClass' => '', 'message' => '郵箱名已存在。'], [['password', 'password_repeat'], 'string', 'length' => [6, 20]], ['password', 'checkPassword'], ['password_repeat','compare','compareAttribute' =>'password','message'=>'兩次輸入的密碼不一致。'], ];}public function register(){ //處理一些東西 //註冊相關的 return false;}public function attributeLabels(){ return [ 'email' => '郵箱', 'password' => '密碼', 'password_repeat' => '重複密碼', ];}public function checkPassword($attribute, $params){ if (!ctype_alnum($this->$attribute)) { $this->addError($attribute, '必須包含字母或數字。'); }}
}
checkPassword 這個獨立驗證器 使用不了 我代碼書寫有問題嗎 各位大哥們
寫法是正確的,你是憑什麼判定不能使用的呢?
這是我的測試案例:
class TestModel extends \yii\base\Model{ public $password; public function rules() { return [ ['password', 'checkPassword'] ]; } public function checkPassword($attribute, $params) { if (!ctype_alnum($this->$attribute)) { $this->addError($attribute, 'password error'); } }}
test case1:
$model = new TestModel();$model->password = '1121312&&UJ9123/.';$model->validate();var_dump($model->getErrors()); //會列印出有錯誤
test case 2:
$model = new TestModel();$model->password = '1121312';$model->validate();var_dump($model->getErrors()); //無錯誤