Php 验证两个字段';t彼此相等

Php 验证两个字段';t彼此相等,php,yii,yii2,yii2-advanced-app,Php,Yii,Yii2,Yii2 Advanced App,我有一个表格,我可以创建足球比赛。有3个字段主队(下拉列表,用户在其中选择一个队)、客场队(也有下拉列表)和得分字段。因此标记值等于团队id。 例如,我可以选择主队尤文图斯,客队米兰,得分2:2。问题是,我应该验证主队和客队是否相等,所以用户不应该创建与自己对抗的足球比赛队,例如尤文图斯vs尤文图斯。我应该如何验证这些字段(主队、客队)是否彼此不相等 规则方法 public function rules() { return [ [['score'], 'requi

我有一个表格,我可以创建足球比赛。有3个字段
主队
(下拉列表,用户在其中选择一个队)、
客场队
(也有下拉列表)和得分字段。因此
标记值等于
团队id

例如,我可以选择主队
尤文图斯
,客队
米兰
,得分
2:2
。问题是,我应该验证主队和客队是否相等,所以用户不应该创建与自己对抗的足球比赛队,例如
尤文图斯
vs
尤文图斯
。我应该如何验证这些字段(主队、客队)是否彼此不相等

规则方法

 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(); ?>


$items
数组包含团队(名称和ID)

只需使用比较验证程序:


将comparevalue更改为CompareAttribute

谢谢您的回复,我已经尝试过了<代码>['home\u team\u id','compare','compareValue'=>'away\u team\u id','operator'=>','message'=>'请选择一个不同的团队],
但是当我选择home team时,它立即显示错误
请选择一个不同的团队
尽管我没有选择客场团队,我也尝试过,但现在它没有显示任何错误,即使这里有相同的teamsIm new,所以我使用了enter和…:)所以:2。使用
'enableClientValidation'=>false
不通过JS3进行验证。使用ajax验证-它将在您尝试发送表单时进行验证:)Let us.@Yupik链接可能会更改或被删除,从而使此答案无效。您应该将链接中的相关部分添加到答案中。您应该在规则方法中使用“compareAttribute”而不是“CompareAValue”。['rango_desde'、'compare'、'compareAttribute'=>'rango_hasta'、'operator'=>'
['home_team_id', 'compare', 'compareAttribute' => 'away_team_id', 'operator' => '!=', 'message' => 'Please choose a different teams'],