[[+content_image]]
M
M
Maxim Zhgulev2015-12-28 01:45:04
Yii
Maxim Zhgulev, 2015-12-28 01:45:04

Yii2. How to check if one of the two required fields is filled?

Validation rule:

...
[['field1', 'field2'], 'validateFields', 'skipOnEmpty' => false, 'skipOnError' => false],
...

Validation function:
public function validateFields($attribute, $params)
{
    // делаю очистку ошибок обоих полей (это не работает)
    $this->clearErrors('field1');
    $this->clearErrors('field2');
    // проверяю
    if (empty($this->field1) && empty($this->field2)) {
        // в первый input помещаю пустую ошибку (поля идут вертикальным списком)
        $this->addError('field1', '');
        // во второй инпут помещаю саму ошибку
        $this->addError('field2', 'At least one must not be blank.');
        return false;
    }
    return true;
}

For the ActiveForm itself:
...
'enableAjaxValidation' => true,
'enableClientValidation' => false,
...

The essence of the problem. The fields are empty. We pass the focus to the first field, then the second, remove the focus from the second - the ajax validation works, both fields (in turn) are marked as has-error and an error message appears. We transfer the focus to the first field, enter the data, remove the focus from the field, and the error continues to hang on the second field. How to force the form to "revalidate" one field when the value of another field changes?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
C
coderlex, 2015-12-28
@e_s_l

Complete the client-side with a validator.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question