我試圖讓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
完美的作品。不知道你在說什麼場景。我測試了我的代碼,它只適用於我。 –