E
E
elise2017-10-19 18:46:32
Yii
elise, 2017-10-19 18:46:32

How to do conditional validation?

Good evening.
on yii2 I'm trying to validate by condition - if the TIN is entered for 10 characters, then the checkpoint is 9-character, if the TIN is entered for 12 characters, then the checkpoint is not needed.
came out something like this:

['inn', function ($attribute, $params, $validator) {
       if (preg_match('/^[0-9]{12}$/', $this->$attribute) || preg_match('/^[0-9]{10}$/', $this->$attribute)) {
            $this->addError($attribute, 'Инн должен быть 10 или 12 символов.');
       }
}],
[[kpp], 'match', 'pattern' => '/^[0-9]{9}*$/i', 'when' => function ($model) {
        return preg_match('/^[0-9]{10}$/', $this->inn);}
]

somehow here you still need to add a condition about the fact that the checkpoint is not needed with a 12-digit inn, and in general to reach at least some kind of performance. so far not very good,
please tell me, maybe I missed something)

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Timofeev, 2017-10-19
@elise

['kpp', 'string', 'min'=>9, 'max'=>9, 'when'=>function($model){ 
  $l = strlen ($model->inn);
  return ($l == 12);
}],
['kpp', 'required', 'when'=>function($model){ 
    $l = strlen ($model->inn);
    return ($l != 12);
],

F
Fudo Tsukiko, 2017-10-19
@FudoTsu

$attribute = intval($attribute);
if(empty($attribute) || preg_match('/^\d{12}$/', $attribute))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question