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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33071345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:21:53  来源:igfitidea点击:

Yii2: ActiveForm field numeric, length => 8

phpyii2yii2-advanced-app

提问by webeno

I'm trying to make yii2 to validate my ActiveFormfield that should be numeric and of 8 characters long.

我正在尝试让 yii2 验证我的ActiveForm字段,该字段应该是数字且长度为 8 个字符。

Following is what I tried in the default LoginFormmodel of yii2/advanced/backend, but unfortunately the isNumericvalidator simply doesn't kick in:

以下是我在 的默认LoginForm模型中尝试过的yii2/advanced/backend,但不幸的是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.');
        }
    }
}

I also tried adding a scenario as suggested in a related post (https://stackoverflow.com/a/27817221/2037924) but that only worked (as in displayed the error) if I did not include the passwordfield in the scenario.

我还尝试按照相关帖子(https://stackoverflow.com/a/27817221/2037924)中的建议添加一个场景,但只有在我没有password在场景中包含该字段时才有效(如显示的错误所示)。

Is this a good way to achieve this at all, or can you think of a better way of doing it?

这是实现这一目标的好方法,还是您能想到更好的方法?

Note:the reason I define usernameas stringis because the numbers may contain leading 0's.

注意:我定义username为的原因string是因为数字可能包含前导 0。

回答by Insane Skull

Try with integerdata type:

尝试使用integer数据类型:

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

It will validate both numericand length. This will do the trick.

它将验证numericlength。这将解决问题。

回答by Mihai P.

Read more about the validations here: http://www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#number

在此处阅读有关验证的更多信息:http: //www.yiiframework.com/doc-2.0/guide-tutorial-core-validators.html#number

This works fine for me using the contact form from yii2-basic

这对我来说很好用 yii2-basic 的联系表格

/**
 * @return array the validation rules.
 */
public function rules()
{
    return [
        // name, email, subject and body are required
        [['name', 'email', 'subject', 'body'], 'required'],
        // email has to be a valid email address
        ['email', 'email'],
        ['subject', 'is8NumbersOnly'],
        // verifyCode needs to be entered correctly
        ['verifyCode', 'captcha'],
    ];
}

public function is8NumbersOnly($attribute)
{
    if (!preg_match('/^[0-9]{8}$/', $this->$attribute)) {
        $this->addError($attribute, 'must contain exactly 8 digits.');
    }
}

回答by Anatolii Dev

public function rules()
{
    return [
        // username should be numeric
        ['username', 'match', 'pattern' => '/^\d{8}$/', 'message' => 'Field must contain exactly 8 digits.],

        // ...
    ];
}

回答by Behrooz Moghaddam

try this:

尝试这个:

public function rules()
{
return [
    // name, email, subject and body are required
    [['name', 'email', 'subject', 'body'], 'required'],
    // email has to be a valid email address
    ['email', 'email'],
    [['subject'], 'number'],
    [['subject'], 'string', 'max' => 8, 'min' => 8],
    // verifyCode needs to be entered correctly
    ['verifyCode', 'captcha'],
];
}