在laravel中使用required_with进行验证,作为数组输入?

时间:2016-08-05 09:54:18

标签: laravel-5

我有一个表格,其复选框为数组,文本框也为数组。我想要实现的是当用户选中一个复选框时,它应该验证输入文本框不是空的。

public function roombooking(Request $request)
    {


      $messsages = array(
        'check.required'=>'No room was selected.Please select room to proceed for booking !',
        'txtnos.required|numeric'=>'Please enter no of persons',
    );
      $rules = array(
        'check'=>'required',
        'txtnos'=>'required_with:data', //txtnos is a array input filed  and data is a array checkbox 
        );
      $validator = Validator::make($request->all(),  $rules,$messsages
            );
      if ($validator->fails()) {

            return Redirect::back()
                ->withErrors($validator)
                ->withinput();

        }
}

Html代码


<table class="table table-hover"  data-toggle="table"  id="table"
data-click-to-select="true">
    <thead>
        <tr>
            <th style="width:10%;" data-field="ActivityId">Select</th> 
            <th style="width:30%;" data-field="ActivityName">Activity Name</th>
            <th style="width:30%;" data-field="Rate">Rate/Person</th>
            <th style="width:30%;">Nos. of person</th>
        </tr>
    </thead>
    <tbody>                
           @foreach($loadactivity as $key=>$activity)
           <tr>
               <td>
                   <input type="checkbox" name="data[]"  value="0;{!! $activity->ActivityId !!};{!! $activity->Rate !!};0;0;{!! $activity->ActivityName !!}" />
               </td>
               <td>{!! $activity->ActivityName !!}</td>
               <td>{!! $activity->Rate !!}</td>
               <td >{!! Form::text('txtnos[]','',['class' => 'form-control small-textbox  ','txtnoid'=>$activity->ActivityId]) !!}</td>
           </tr>
           @endforeach
    
     </tbody>
</table>

请帮帮我

1 个答案:

答案 0 :(得分:4)

更改表单:

...
<td><input type="checkbox" name="row[{{$key}}][data]" value="0;{!! $activity->ActivityId !!};{!! $activity->Rate !!};0;0;{!! $activity->ActivityName !!}" />
</td>
<td>{!! $activity->ActivityName !!}</td>
<td>{!! $activity->Rate !!}</td>
<td>{!! Form::text('row[{{$key}}][txtnos]','',['class' => 'form-control small-textbox  ','txtnoid'=>$activity->ActivityId]) !!}</td>
...

所以唯一改变的是数据和txtnos的名称,它将为您提供以下内容:

$exampleResult = [
    'row' => [
        // old $key as new key
        0 => [
            'txtnos' => 'entered value',
            'data' => '1', // But only if checked
        ],
        1 => [
            'txtnos' => 'entered value',
            'data' => '1', // But only if checked
        ],
    ]
];

验证规则

$rules = [
    'row.*.txtnos' => 'required_with:row.*.data'
];

在示例中,如果设置了同一行中的txtnos,则每行需要data

验证消息

$messages = [
    'row.*.txtnos.required_with' => 'Enter a value or uncheck the checkbox..'
];

重要:
在Laravel 5.2中添加了.*.的验证,您没有指定您的确切版本,所以我不确定它是否适合您。无论如何,还有另一种方法可以做到这一点。

对于版本&lt; 5.2,循环输入行并用我的例子中的*替换当前键。