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

标签 php yii yii2 yii2-advanced-app

我有一个可以创建足球比赛的表格。有3个字段home team (下拉列表,用户在其中选择团队),away team (也是下拉列表)和分数字段。所以<option>标签值等于 team_idprintscreen

例如,我可以选择主队juventus ,客队milan并得分 2:2 。问题是,我应该验证主队是否不等于客队,因此用户不应该创建自己的足球比赛球队,例如 juventusjuventus 。我应该如何验证这些字段(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)

最佳答案

只需使用比较验证器:Docs

关于php - 验证两个字段不应彼此相等 yii2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40997003/

相关文章:

php - 使用 jquery/css3 在语音气泡中显示错误消息

php - 是否有可以从共享主机环境实际运行的任何 PHP(或类似)版本的 Google Caja?

authentication - Yii::app()-> user-> isGuest始终返回true,即使登录成功

javascript - 在 Yii 上包含 JS 文件

mysql - Yii2 OrderBy特定字段值优先

php - 在 MySQL 中提取 MAX() 值时出现问题

javascript - 表单提交期间的 php 确认消息

php - Yii 一个 actionIndex() 用于数据库中的 4 个表

php - 如何设置YII2多数据库可配置?

php - Yii2 - Filsh OAuth2 服务器安装