[[+content_image]]
H
H
hollanditkzn2017-08-23 17:17:44
Yii
hollanditkzn, 2017-08-23 17:17:44

How to do validation for phone format?

There is a MaskedInput widget, but the problem is that it does not pass
validation Client.php

public function rules()
    {
        return [
            [['name', 'phone'], 'required', 'on' => self::SCENARIO_DEFAULT],
            [['phone'], 'number'],
            [['phone'], 'filter', 'filter' => function($value){
                return str_replace(['(', ')', '-'], '', $value);
            }],
            [['phone'], 'unique'],
        ];
    }

And in the view
<?= $form->field($model, 'phone')->widget(MaskedInput::className(),[
        'mask' => '8(999)999-99-99',
    ]) ?>

If you follow the documentation, then an array can be used there, but for some reason the validation always comes out that the phone must be an integer
In the database, the type is decimal

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
H
hollanditkzn, 2017-08-24
@hollanditkzn

I did it a little differently. In the database I did it as a string and I did the validation using a regular expression

[['phone'], 'string'],
            ['phone', 'match', 'pattern' => '/^(8)[(](\d{3})[)](\d{3})[-](\d{2})[-](\d{2})/', 'message' => 'Телефона, должно быть в формате 8(XXX)XXX-XX-XX'],

A
Alexey Marchenkovsky, 2017-08-23
@fun4life

Good afternoon!
Already in several projects I use https://github.com/udokmeci/yii2-phone-validator .
In addition to phone validation, it can also format the entered number according to the selected format, so that all numbers in the database are stored in the same form.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question