【问题标题】:validate two fields shouldn't equal to each other yii2验证两个字段不应该彼此相等yii2
【发布时间】:2023-04-08 03:53:01
【问题描述】:

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

例如,我可以选择主队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' => ' 'number'],

标签: php yii yii2 yii2-advanced-app


【解决方案1】:

只需使用比较验证器:Docs

【讨论】:

  • 感谢回复,我已经试过了。 ['home_team_id', 'compare', 'compareValue' =&gt; 'away_team_id', 'operator' =&gt; '==', 'message' =&gt; 'Please choose a different teams'], 但是当我选择主队时它立即显示错误Please choose a different teams 尽管我还没有选择客队
  • 我也试过了,现在没有报错,即使是同一个团队
  • 我是新来的,所以我使用了 enter 和... :) 所以:2. 使用 'enableClientValidaton' =&gt; false 不通过 js 验证 3. 使用 ajax 验证 - 当你尝试发送表单时它会验证:)
  • @Yupik 链接可以更改或删除,因此使此答案无效。您应该将链接中的相关部分添加到答案中。
【解决方案2】:
['home_team_id', 'compare', 'compareAttribute' => 'away_team_id', 'operator' => '!=', 'message' => 'Please choose a different teams'],

将 comparevalue 更改为 CompareAttribute

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多