godot
godot

Reputation: 3545

Model form rules and validation in Yii2

For example I have model form MySubmitForm:

use yii\base\Model;

class MySubmitForm extends Model{


    public $value1;
    public $value2;
    public $value3;

    public function rules(){
         return [['value1', 'value2'],'required'];
    }

}

Here I have two required parameters ($value1, $value2) and I want one of them to be required or I want to user got error only when both $value1 and $value2 would be empty.

Can I achieve this from this form model?

Upvotes: 1

Views: 476

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23738

You can use Custom validation function inside your validation rules.

Possible options:

1) Select the most important relevant field and add error to it.

2) Select multiple important relevant fields and add the same error message to them (we can store and pass message in a separate variable before passing to keep code DRY).

3) We can use not existing attribute name for adding error, let's say all because attribute existence is not checked at that point.

public function rules()
{
    return [['value1', 'value2'],'yourCustomValidationMethod'];
}

public function yourCustomValidationMethod()
{
    // Perform custom validation here regardless of "name" attribute value and add error when needed
    if ($this->value1=='' && $this->value2=='') {
        //either use session flash 
        Yii::$app->session->setFlash('error','You need to provide one of the fields');

        //or use model error without any specific field name 
        $this->addError('all', 'Your error message');
    }            
}

Note you can use either session flash or model to notify the error use which every you like

Upvotes: 1

Related Questions