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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀