我试图让yii2来验证我的ActiveForm
字段应该是数字和8个字符长。Yii2:ActiveForm字段数字,长度=> 8
下面是我试过在yii2/advanced/backend
默认LoginForm
模式,但不幸的是,isNumeric
验证只需在不踢:
public function rules()
{
return [
// username and password are both required
[['username', 'password'], 'required'],
// username should be numeric
['username', 'isNumeric'],
// username should be numeric
['username', '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),但只有在该场景中没有包含password
字段的情况下才起作用(如显示错误)。
这是一个很好的方法来实现这一点,或者你能想出一个更好的方法吗?
注:我定义username
为string
的原因是因为数字可能包含前导0。
对不起,但这将如何使它8位数字,也考虑领先0? – webeno
nope,不工作(没有这种情况),我在用户名字段中输入了一个带有字母的简单字符串,它验证了正常。再次,它适用于这种情况,但只有当我离开密码字段时才有效。我相信问题不在于验证器功能,而在于处理场景的方式,或者2验证器不会“一起工作”(?)...认真,不知道,因此我的问题... – webeno
完美的作品。不知道你在说什么场景。我测试了我的代码,它只适用于我。 –