2016-12-06 45 views
0

我有一個表單,我可以創建足球比賽。有3個字段home team(下拉列表,其中用戶選擇一個團隊),away team(也下拉列表)和分數字段。所以<option>標籤值等於team_idprintscreen驗證兩個字段不應該等於對方yii2

例如,我可以選擇主隊juventus,客隊milan和得分2:2。問題是,我應該驗證主隊是否不等於客隊,所以用戶不應該創建自己的足球比賽隊,例如juventus vs juventus。我應該如何驗證這些字段(home_team,away_team)不相等?

規則方法

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)

+0

你應該使用 'compareAttribute'而不是規則方法中的'compareValue'。 ['rango_desde','compare','compareAttribute'=>'rango_hasta','operator'=>'<', 'type' =>'number'], –

回答

0

只需使用比較驗證:Docs

+0

感謝您的回覆,我已經嘗試過了。 '['home_team_id','compare','compareValue'=>'away_team_id','operator'=>'==','message'=>'請選擇不同的球隊','但是當我選擇主隊時它立即顯示錯誤「請選擇一個不同的球隊」,儘管我沒有選擇走隊 –

+0

1.你在這裏有錯誤的運算符,它應該是'!=' – Yupik

+0

我也試過了,但現在它不顯示任何錯誤,甚至如果有相同的球隊 –