D
D
Dmitry Kim2017-07-24 16:14:37
Yii
Dmitry Kim, 2017-07-24 16:14:37

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; /* это тоже не работает, так как проверка идет дальше */
        }
    ]
]

It seems that you don’t want to “fence the garden”, creating a separate function for validation, because “as if” there is a built-in one. Perhaps it is still possible to "persuade" the framework? Or not?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
Dmitry Kim, 2017-07-26
@kimono

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 question

Ask a Question

731 491 924 answers to any question