douji6896
2016-12-06 13:53
浏览 171
已采纳

验证两个字段不应该彼此相等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)

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • du59131 2016-12-06 13:57
    已采纳

    Just use Compare Validator: Docs

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dqiaw48488 2019-04-25 06:31
    ['home_team_id', 'compare', 'compareAttribute' => 'away_team_id', 'operator' => '!=', 'message' => 'Please choose a different teams'],
    

    change comparevalue to CompareAttribute

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题