dpge74512 2015-02-04 23:53
浏览 297
已采纳

在Laravel中显示输入数组的验证错误

I am submitting an array of inputs to my controller like so:

<input id="box-1-nickname" name="box-nickname[]" class="form-control" type="text" placeholder="Required">
<input id="box-2-nickname" name="box-nickname[]" class="form-control" type="text" placeholder="Required">

I am doing some validation like this:

$validator = Validator::make(Input::all(), array(
        'supplies-count' => 'required|in:0,1,2,3,4',
    ));

$arrayValidator = Validator::make(Input::all(), []);

$arrayValidator->each('box-nickname', ['required|min:1|max:60']);

if( $validator->fails() || $arrayValidator->fails() ) {
    return Redirect::route('route-2')
           ->withErrors($arrayValidator)
           ->withInput();
}

The problem is when I try to check the errors like this it doesn't work:

if( $errors->has('box-1-nickname') ) { echo ' has-error'; }
  • 写回答

3条回答 默认 最新

  • duannian3494 2015-11-10 20:53
    关注

    You've probably long found a solution, but for anyone else who stumbles across this:

    The validator uses array dot notation of the field array keys. For example box-nickname[0] becomes box-nickname.0

    Therefore if( $messages->has('box-nickname.0') ) { echo ' has-error'; } should give you your desired result. However, you will need to dynamically generate the array key since as you've said, you won't know how many box-nicknames are being applied. I use this in my form view:

    @if(!is_null(Input::old('box-nickname')))
        @foreach(Input::old('box-nickname') as $n => $box-nickname)
            @include('box-nickname-create-form-partial')
        @endforeach
    @endif
    

    Then create a partial view called "box-nickname-create-form-partial.blade.php" or whatever you want to call it with the form field, which might look something like this:

    <div class="form-group {!! $errors->has('box-nickname.'.$n) ? ' has-error' : '' !!}">
        <input name="box-nickname[{{$n}}]" class="form-control" type="text" placeholder="Required">
    </div>
    

    I hope that's helpful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c