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

验证两个字段不应该彼此相等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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c