本文介绍了在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">

我正在做这样的验证:

$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'; }

推荐答案

您可能很早就找到了解决方案,但是对于任何偶然发现此问题的人来说:

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

验证器使用字段数组键的数组点表示法.例如,box-nickname[0]变为box-nickname.0

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

因此,if( $messages->has('box-nickname.0') ) { echo ' has-error'; }应该会为您提供所需的结果.但是,您将需要动态生成数组键,因为如上所述,您将不知道要应用多少个框昵称.我在表单视图中使用它:

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

然后创建一个名为"box-nickname-create-form-partial.blade.php"的局部视图,或使用表单字段调用的任何视图,它可能类似于以下内容:

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>

我希望这会有所帮助.

这篇关于在Laravel中显示来自输入数组的验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:49