如何显示输入数组的验证错误?

时间:2018-11-12 07:32:57

标签: php laravel validation laravel-5

如何在 LARAVEL 中显示验证错误消息,我们将输入数组设置为:

<input type="text" name="start_time[]" class="form-control start_time" value="" >

因为, start_time => 'required', 在这里不起作用

2 个答案:

答案 0 :(得分:1)

您应该尝试以下操作:

$validator = Validator::make($request->all(), [
    "start_time.*"  => "required",
]);

更新后的答案

$validator = $request->validate([
    "start_time"    => "required|array|min:10",
    "start_time.*"  => "required",
]);

答案 1 :(得分:0)

您的规则必须是这样的:

'start_time.*' => 'required'

我通过以下详细信息测试了您的情况,一切正常。

视图:

<form action="{{ route('test.store') }}" method="post">
    {{ csrf_field() }}

    <input type="text" name="start_time[]" class="form-control start_time" value="" >

    <input type="text" name="start_time[]" class="form-control start_time" value="" >

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

控制器:

public function store(Request $request)
{
    $request->validate([
        'start_time.*' => 'required'
    ]);

表单为空白时出错:

The start_time.0 field is required.
The start_time.1 field is required.