验证规则无法正常工作 - 用户应该只能为一种票证类型选择数量

时间:2018-04-23 00:42:55

标签: php laravel

我有下面的表格,用户可以为每种票据类型选择他想要的数量。每种票证类型都有最小值和最大值,用户只应选择允许的值,因此我在下面有一个客户规则。

问题在于,例如当用户访问表单以选择他想要的每种票证类型的数量时,如果会议有4种票证类型并且他选择数量,例如数量“1”,仅用于一种票据类型并单击“下一步”,它将显示验证消息“您只能选择选择菜单中的可用数量”。仅当用户选择所有故障单类型的数量时,才会显示验证错误。

但是用户应该只能为一种票类选择数量。你知道这是什么问题吗?

自定义规则:

class TicketTypeQuantity implements Rule{
    public function passes($attribute, $value)
    {
       foreach($value as $key=>$v){
            $ttype = TicketType::where('name',$key)->first();
            if ( $v < $ttype->min || $v > $ttype->max)
                return false;
        }
        return true;
    }

    public function message()
    {
        return 'You can only select the quantities available in the select menu';
    }
}

表单,用户可以在其中选择每种产品的数量。

<form method="post" action="{{route('congresses.storeQuantity', ['id' => $cong->id, 'slug' => $cong->slug])}}">
  <ul class="list-group list-group-flush">
          {{ csrf_field() }}
          @foreach($ttypes as $ttype)
              <li class="list-group-item">
                      <span>{{$ttype->name}}</span>
                  </div>
                  <select class="custom-select form-control" name="ttypes[{{ $ttype->name }}]">
                      <option selected></option>
                      @for ($i = $ttype->min; $i <= $ttype-> max; $i++)
                          <option value="{{ $i }}">{{ $i }}</option>
                      @endfor
                  </select>
                  <span>{{$ttype->showPrice()}}</span>
              </li>
          @endforeach
  </ul>
  <input type="submit" class="float-right btn btn-primary" value="Next" />
  </form>

storeQuantity方法:

public function storeQuantity(Request $request, $id, $slug = null){
        $request->validate([
            'ttypes' => ['required', 'array', new TicketTypeQuantity ],
        ]);

        $ttypeQuantities = $request->get('ttypes');

        $all_participants = Congress::where('id', $id)->first()->all_participants;

        foreach($ttypeQuantities as $ttypeName => $quantity){

            $ttype = TicketType::where('name', $ttypeName)->firstOrFail();
            $price = $ttype->price;

            $selectedTypes[$ttype->name]['quantity'] = $quantity;
            $selectedTypes[$ttype->name]['price'] = $price;
            $selectedTypes[$ttype->name]['subtotal'] = $price * $quantity;
        }
        Session::put('selectedTypes', $selectedTypes);
        Session::put('all_participants' , $all_participants);
        return redirect(route('congresses.registration',['id' => $id, 'slug' => $slug]));
    }

1 个答案:

答案 0 :(得分:1)

由于您循环显示所选值,因此您未明确允许nullable值,因此您需要修改条件以允许nullable值,如下所示:

if ( ($v < $ttype->min || $v > $ttype->max) && $v != null)

您可以省略具有空值的选定值,如下所示:

foreach($ttypeQuantities as $ttypeName => $quantity){
  if($quantity) {
    // your code goes here
  }
}