devnull Ψ
devnull Ψ

Reputation: 4029

validate two fields shouldn't equal to each other yii2

i have a form where i can create football match. there are 3 fields home team (drop down list, where user selects a team), away team(also drop down list) and score field. so <option> tag value equals team_id. printscreen

for example, i can choose home team juventus, away team milan and score 2:2. problem is, i should validate if home team not equals to away team, so user shouldn't create football match team against itself, for example juventus vs juventus. how should i validate these fields(home_team, away_team) not equal to each other?

rules method

 public function rules()
 {
    return [
        [['score'], 'required'],
        ['home_team_id', 'required', 'message' => 'Please choose a home team'],
        ['away_team_id', 'required', 'message' => 'Please choose a away team'],
        ['score', 'match', 'pattern' => '/^\d{1,2}(:\d{1,2})?$/'],
        ['home_team_id', 'compare', 'compareValue' => 'away_team_id', 'operator' => '!=', 'message' => 'Please choose a different teams'],
        [['away_team_id'], 'exist', 'skipOnError' => true, 'targetClass' => Team::className(), 'targetAttribute' => ['away_team_id' => 'id']],
        [['home_team_id'], 'exist', 'skipOnError' => true, 'targetClass' => Team::className(), 'targetAttribute' => ['home_team_id' => 'id']],
        [['round_id'], 'exist', 'skipOnError' => true, 'targetClass' => Round::className(), 'targetAttribute' => ['round_id' => 'id']],
    ];
  }

my form

<?php $form = ActiveForm::begin(); ?>

<?= $form->field($model, 'home_team_id')->dropDownList($items, $params)->label('Home Team');?>

<?= $form->field($model, 'away_team_id')->dropDownList($items, $params)->label('Away Team');?>

<div class="hidden">
    <?= $form->field($model, 'round_id')->hiddenInput()->label(''); ?>
</div>

<?= $form->field($model, 'score')->textInput([
    'maxlength' => true,
    'placeholder' => 'seperate goals with colon, for example 2:1'
]) ?>

<div class="form-group">
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

$items array contains teams(names and ids)

Upvotes: 2

Views: 4281

Answers (2)

Prabu Karana
Prabu Karana

Reputation: 302

['home_team_id', 'compare', 'compareAttribute' => 'away_team_id', 'operator' => '!=', 'message' => 'Please choose a different teams'],

change comparevalue to CompareAttribute

Upvotes: 1

Yupik
Yupik

Reputation: 5032

Just use Compare Validator: Docs

Upvotes: 2

Related Questions