我有一个表单,我可以创建足球比赛。有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'], –