Answer the question
In order to leave comments, you need to log in
How to “concisely” validate one field with a match validator in Yii2 using a template from another field of the same form?
For the needs of the admin panel, I use settings models a la "Key - Value".
Let's say we create a hidden form field, where we will specify a template for validating the "Value" field. And let's call it "Pattern". Those. our model is something like "Key - Value - Fill Pattern".
To use the validator, add the rule:
[
//...
[['value'], 'match',
'pattern' => /* $this->pattern - не работает, так как для пустых значение сразу выскакивает исключение RegularExpressionValidator-а */,
'when' => function($model) {
return $model->pattern; /* это тоже не работает, так как проверка идет дальше */
}
]
]
Answer the question
In order to leave comments, you need to log in
In general, using the standard validator in this way, we can run into an exception if we specify a clumsy template. Decided to do this:
[
['value'],
function ($attribute, $params, $validator) {
try {
if (!preg_match($this->pattern, $this->{$attribute})) {
$this->addError($attribute, 'Значение не соответствует требуемому шаблону');
}
} catch (\Exception $e) {
$this->addError('pattern', 'Шаблон указан некорректно');
}
},
'when' => function ($model) {
return $model->pattern;
},
],
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question