Yii2: ActiveForm field numeric, length => 8
Try with integer
data type:
[['username'], 'integer'],
[['username'], 'string', 'min' => 8],
It will validate both numeric
and length
. This will do the trick.
Read more about the validations here: 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
/**
* @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.');
}
}