A
A
Ann20162016-07-03 13:48:40
Yii
Ann2016, 2016-07-03 13:48:40

How to implement the work of your validator in the form?

It turned out to make my own validator, but there are problems with validation during data entry. If the user submits the model, then I can validate the data, but already in the controller, but how can I make the validation take place during the data entry into the form and give errors before submitting the form?
The model has the following rules

[['phone'], PhoneValidator::className()],
            [['phone', 'mail', 'name', 'country'], 'required'],

The component responsible for validation
namespace frontend\components;

use yii\validators\Validator;
use \libphonenumber\PhoneNumberUtil;

class PhoneValidator extends Validator
{
    public function validateAttribute($model, $attribute)
    {
        $phoneUtil = PhoneNumberUtil::getInstance();
        try {
            $swissNumberProto = $phoneUtil->parse($model->$attribute, $model->country);
            $numberExample = $phoneUtil->getExampleNumberForType($model->country, \libphonenumber\PhoneNumberType::MOBILE);

            if (!$phoneUtil->isValidNumber($swissNumberProto)) {
                $model->addError($attribute, ('Input phone is wrong. Example of inputting is {numberExample}' ));
            } else {
                $model->$attribute = $phoneUtil->format($swissNumberProto, \libphonenumber\PhoneNumberFormat::INTERNATIONAL);
            }
        } catch (\libphonenumber\NumberParseException $e) {
            $model->addError($attribute,  'Input phone is wrong');
        }
    }
}

And the actual form
<?php $form = ActiveForm::begin(['action' => ['main/create']]); ?>
            <?= $form->field($model, 'country')->dropDownList($contries) ?>
            <?= $form->field($model, 'phone')->textInput() ?>
<?php ActiveForm::end(); ?>

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Andrey Pavlenko, 2016-07-03
@Ann2016

www.yiiframework.com/doc-2.0/yii-validators-valid...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question