Answer the question
In order to leave comments, you need to log in
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'],
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');
}
}
}
<?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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question