我正在尝试使yii2验证我的ActiveForm字段,该字段应为数字且长度为8个字符.
@H_301_12@以下是我在yii2 / advanced / backend的默认LoginForm模型中尝试过的,但不幸的是isNumeric验证器根本没有启动:
public function rules() { return [ // username and password are both required [['username','password'],'required'],// username should be numeric ['username','isNumeric'],'string','length'=>8],// password is validated by validatePassword() ['password','validatePassword'],]; } /** * Validates if the username is numeric. * This method serves as the inline validation for username. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function isNumeric($attribute,$params) { if (!is_numeric($this->username)) $this->addError($attribute,Yii::t('app','{attribute} must be numeric',['{attribute}'=>$attribute])); } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute,$params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute,'Incorrect username or password.'); } } }
我还尝试添加一个相关帖子(https://stackoverflow.com/a/27817221/2037924)中建议的场景,但只有在场景中没有包含密码字段时才会起作用(如显示错误).
注意:我将用户名定义为字符串的原因是因为数字可能包含前导0.