Yii2: Either one field is required Validation
Asked Answered
S

3

9

I have to implement the validation as mentioned in the title that either one of the two fields (email, phone) is required. I am doing this in my model:

[['email'],'either', ['other' => ['phone']]],

And this is the method:

 public function either($attribute_name, $params) {
        $field1 = $this->getAttributeLabel($attribute_name);
        $field2 = $this->getAttributeLabel($params['other']);
        if (empty($this->$attribute_name) && empty($this->$params['other'])) {
            $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
            return false;
        }
        return true;
    }

When I access my index page, it gives me this error:

Exception (Unknown Property) 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\validators\InlineValidator::0'

Any help?

Saudra answered 10/1, 2017 at 10:25 Comment(4)
Parameters should not be in array.Homelike
Changed the parameters not to be in array, still the same error!Saudra
Try adding curly brackets in empty($this->{$params['other']})Homelike
It gives the syntax error then! @HomelikeSaudra
H
12

The rule should be:

['email', 'either', 'params' => ['other' => 'phone']],

And method:

public function either($attribute_name, $params)
{
    $field1 = $this->getAttributeLabel($attribute_name);
    $field2 = $this->getAttributeLabel($params['other']);
    if (empty($this->$attribute_name) && empty($this->{$params['other']})) {
        $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
    }
}
Homelike answered 10/1, 2017 at 10:58 Comment(1)
shouldn't || not be && if the error should only be added if both attributes are empty?Noellenoellyn
L
16

If you don't care that both fields show an error when the user provides neither of both fields:

This solutions is shorter than the other answers and does not require a new validator type/class:

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

If you want to have a customized error message, just set the message option:

$rules = [
  [
    'email', 'required',
    'message' => 'Either email or phone is required.',
    'when' => function($model) { return empty($model->phone); }
  ],
  [
    'phone', 'required',
    'message' => 'Either email or phone is required.',
    'when' => function($model) { return empty($model->email); }
  ],
];
Lettering answered 14/4, 2019 at 16:4 Comment(1)
If using client-side validation, don't forget to add a clientWhen. See https://mcmap.net/q/790034/-yii2-conditional-validator-always-returns-required for an example.Alpenglow
H
12

The rule should be:

['email', 'either', 'params' => ['other' => 'phone']],

And method:

public function either($attribute_name, $params)
{
    $field1 = $this->getAttributeLabel($attribute_name);
    $field2 = $this->getAttributeLabel($params['other']);
    if (empty($this->$attribute_name) && empty($this->{$params['other']})) {
        $this->addError($attribute_name, Yii::t('user', "either {$field1} or {$field2} is required."));
    }
}
Homelike answered 10/1, 2017 at 10:58 Comment(1)
shouldn't || not be && if the error should only be added if both attributes are empty?Noellenoellyn
H
1

Improved variant

        ['gipsy_team_name', 'either', 'skipOnEmpty'=>false, 'params' => ['other' => 'poker_strategy_nick_name']],
        ['vkontakte', 'either', 'skipOnEmpty'=>false, 'params' => ['other' => ['odnoklasniki','odnoklasniki']]],

Added 'skipOnEmpty'=>false for forcing validating and 'other' can be array

/**
 * validation rule
 * @param string $attribute_name
 * @param array $params
 */
public function either($attribute_name, $params)
{
    /**
     * validate actula attribute
     */
    if(!empty($this->$attribute_name)){
        return;
    }

    if(!is_array($params['other'])){
        $params['other'] = [$params['other']];
    }

    /**
     * validate other attributes
     */
    foreach($params['other'] as $field){
        if(!empty($this->$field)){
            return;
        }
    }

    /**
     * get attributes labels
     */
    $fieldsLabels = [$this->getAttributeLabel($attribute_name)];
    foreach($params['other'] as $field){
        $fieldsLabels[] = $this->getAttributeLabel($field);
    }

    $this->addError($attribute_name, \Yii::t('poker_reg', 'One of fields "{fieldList}" is required.',[
        'fieldList' => implode('"", "', $fieldsLabels),
    ]));

}
Haimes answered 28/9, 2018 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.