验证两个字段不应该彼此相等yii2

时间:2016-12-06 13:53:20

标签: php yii yii2 yii2-advanced-app

我有一个表格,我可以创建足球比赛。有3个字段 app.Use(async (context, next) => { await next(); if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) { context.Request.Path = "/index.html"; context.Response.StatusCode = 200; await next(); } }); (下拉列表,用户选择一个团队),home team(也是下拉列表)和得分字段。因此away team标记值等于<option>printscreen

例如,我可以选择主队team_id,客队juventus和得分milan。问题是,我应该验证主队是否不等于客队,因此用户不应该创建足球比赛队伍,例如2:2 vs juventus。我应该如何验证这些字段(home_team,away_team)彼此不相等?

规则方法

juventus

我的表格

 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']],
    ];
  }

<?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(); ?> 数组包含团队(名称和ID)

2 个答案:

答案 0 :(得分:0)

只需使用比较验证器:Docs

答案 1 :(得分:0)

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

将comparevalue更改为CompareAttribute