我有一個表單,我可以創建足球比賽。有3個字段home team
(下拉列表,其中用戶選擇一個團隊),away team
(也下拉列表)和分數字段。所以<option>
標籤值等於team_id
。 驗證兩個字段不應該等於對方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)
你應該使用 'compareAttribute'而不是規則方法中的'compareValue'。 ['rango_desde','compare','compareAttribute'=>'rango_hasta','operator'=>'<', 'type' =>'number'], –