简体   繁体   English

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

[英]Yii2: ActiveForm field numeric, length => 8

I'm trying to make yii2 to validate my ActiveForm field that should be numeric and of 8 characters long. 我正在尝试使yii2验证我的ActiveForm字段,该字段应为数字且长度为8个字符。

Following is what I tried in the default LoginForm model of yii2/advanced/backend , but unfortunately the isNumeric validator simply doesn't kick in: 以下是我在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.');
        }
    }
}

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 password field 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 username as string is because the numbers may contain leading 0's. 注意:我将username定义为string的原因是因为数字可能包含前导0。

Try with integer data type: 尝试使用integer数据类型:

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

It will validate both numeric and length . 它将验证numericlength This will do the trick. 这样就可以了。

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

        // ...
    ];
}

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'],
];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM