gpt4 book ai didi

php - Yii2:ActiveForm 字段数字,长度 => 8

转载 作者:可可西里 更新时间:2023-11-01 12:44:52 25 4
gpt4 key购买 nike

我正在尝试让 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。

最佳答案

尝试使用 integer 数据类型:

[['username'], 'integer'],
[['username'], 'string', 'min' => 8],

它将验证numericlength。这将达到目的。

关于php - Yii2:ActiveForm 字段数字,长度 => 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com