【问题标题】:Laravel exists validation if the given value is not zero如果给定值不为零,Laravel 存在验证
【发布时间】:2019-12-10 20:06:18
【问题描述】:

这是我的情况:

假设我的 html 表单中有一个 radio input,它的值必须存在于表中只有当用户检查其中一个时,否则该值必须是zero

这是我的结构:

<div class="inputGroup">
    <input id="first_change1" name="first_change" type="radio" value="{{ $game->teamOne->id }}" {{ old('first_change') == $game->teamOne->id ? 'checked="checked"' : '' }} />
    <label for="first_change1" class="farsi">{{ $game->teamOne->name }}</label>
</div>
<div class="inputGroup">
    <input id="first_change2" name="first_change" type="radio" value="{{ $game->teamTwo->id }}" {{ old('first_change') == $game->teamTwo->id ? 'checked="checked"' : '' }} />
    <label for="first_change2" class="farsi">{{ $game->teamTwo->name }}</label>
</div>
<div class="inputGroup">
    <input id="first_change3" name="first_change" type="radio" value="0" {{ old('first_change') == "0" ? 'checked="checked"' : '' }} />
    <label for="first_change3" class="farsi">None of them</label>
</div>
@if( $errors->has('first_change'))
    <h6 class="alert alert-danger farsi text-danger rtl text-right">
        {{ $errors->first('first_change') }} <i class="fa fa-2x fa-arrow-up fleft" style="bottom: 5px !important;"></i>
    </h6>
@endif

这是我目前对该字段的验证:

'first_change' => 'required|exists:fc_teams,id',

但我需要这样的东西:

'first_change' => 'required|[IF VALUE IS NOT -0-; THEN]exists:fc_teams,id',

【问题讨论】:

  • 你选择0而不是null有什么原因吗?
  • @Rwd 是的,因为我的数据库字段是整数而不是 null 所以...

标签: laravel validation laravel-5


【解决方案1】:

您可以有条件地构建您的验证:

$first_change_validation = [
    'required',
];
if ($request->get('first_change') == 0) {
    $first_change_validation[] = 'exists:fc_teams,id';
}

然后在你的验证中使用这个数组:

$this->validate($request, [
    'first_change' => $first_change_validation,
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-24
    • 2018-06-24
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 2017-08-22
    相关资源
    最近更新 更多