Validation for form

62 Views Asked by At

Please help with setting rules (). The thing is, I have a form. Where 2 fields are present. If all fields are empty, the form cannot be submitted, but if at least ONE is not empty, then the form can be submitted. Can you help me please, I'm new at it?

Here's my form

<?php $form = ActiveForm::begin() ?>
     $form->field($model, 'field1')->textInput();
     $form->field($model, 'field2')->textInput();
<?php $form = ActiveForm::end() ?>

And this's my model, but this rule does not quite suit me. Because the rules require you to fill in all the fields. And the main thing for me is that at least one, but was filled, so i could send the form. If ALL fields are empty, then validation fails.

public function rules()
    {
        return [
            [['field1', 'field1'], 'require'] ]}

Should I add something in controller maybe?

3

There are 3 best solutions below

0
On

You have TYPO in rules: use required

public function rules()
{
    return [
        [['field1', 'field1'], 'required']
    ];
}
0
On

You can use standalone validation:

public function rules()
{
    return [
        [['field1', 'field2'], MyValidator::className()],
    ];
}

And create a new class like follows:

namespace app\components;

use yii\validators\Validator;

class MyValidator extends Validator
{
   public function validateAttribute($model, $attribute)
   {
    if (empty($model->filed1) and empty($model->field2)) {
        $this->addError($model, $attribute, 'some message');
    }
}

}

0
On

You can use yii\validators\Validator::when property to decide whether the rule should or shouldn't be applied.

public function rules()
{
    return [
        [['field1'], 'required', 'when' => function ($model) { 
            return empty($model->field2); 
        }]
        [['field2'], 'required', 'when' => function ($model) { 
            return empty($model->field1); 
        }]
    ];
}

The when property is expecting a callable that returns true if the rule should be applied. If you are using a client side validation you might also need to set up the yii\validators\Validator::whenClient property.