Liam
Liam

Reputation: 536

Yii2 Custom Standalone Validation

OK, I believe I will have many custom validations so I have decided to create a standalone validation class as per Yii Standalone Validation Doc.

This particular validator is to make sure either company_name or name is filled in, so Either Required.

I have created the class in app\components\validators\BothRequired.php

<?php
namespace app\components\validators;
use Yii;
use yii\validators\Validator;

class BothRequired extends Validator
{
    public function validateAttribute($model, $attribute)
    {
       //validation code here
    }
}

Here is the model

public function rules()
{
    return [
        ['company_name', BothRequired::className(), 'skipOnEmpty' => false, ],
    ];
}

However this validation requires some params to be passed to the validation in this example I need to send the second attribute that is needed to be checked against. I cannot seem to work out how to do this, if I create the validation rule in the model itself then I can pass $params but i dont know how to pass to this standalone class.

Also on a further note, what would be a lot better for me is if I could have a class with all my custom validators in it rather than a file per validator.

Any ideas?

Regards

Upvotes: 1

Views: 4333

Answers (1)

Liam
Liam

Reputation: 536

OK,

With the help of @gandaliter I have found the answer

Validator class

namespace app\components\validators;
use Yii;
use yii\validators\Validator;

class BothRequired extends Validator
{
    public $other;
    public function validateAttribute($model, $attribute)
    {
        if (empty($model->$attribute) && empty($model->{$this->other})) {
            $this->addError($model, $attribute, 'Either '.$attribute.' or '.$this->other.' is required!');
            $this->addError($model, $this->other, 'Either '.$attribute.' or '.$this->other.' is required!');
        }
    }
}

Model rule

public function rules()
{
    return [
        ['company_name', BothRequired::className(), 'other'=>'contact_name', 'skipOnEmpty' => false, ],
    ];
}

As you can see you have to declare the property you are going to send over in this case it is $other and then use it in the code as $this->other

I can then validate both items.

I hope this clears it up

Liam

P.S. On the other note I mentioned.... How would be able to put all validators in one class?

Upvotes: 5

Related Questions