Laravel 5.3自定义验证消息数组

时间:2017-06-16 18:45:10

标签: php laravel laravel-5.3 laravel-blade laravel-request

我正在使用Laravel 5.3,我尝试为Request Class中最大长度的每个字符串设置自定义消息,如...

<?php

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class UpdateRecordRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        $rules = [
            'field_1' => 'string|max:100',
            'field_2' => 'string|max:100',
            'field_3' => 'string|max:100',
            ];

        return $rules;
    }

    public function messages()
    {
        return [
            '*.max' => ['string' => 'Insert some value.']
       ];
    }

}

但是当我提交表单时,会出现一个错误,在MessageBag.php第245行中说&#34; ErrorException:&#34;以及必须显示错误时的视图文件。

这是观点...

    <div class="form-group {{ $errors->has('field_1') ? 'has-error' : '' }}">
        <label for="">Field 1</label>
        {{ Form::text('field_1', $record->field_1, ['class' => 'form-control']) }}
        <span class="help-block">{{ $errors->first('field_1') }}</span>
    </div>

    <div class="form-group {{ $errors->has('field_2') ? 'has-error' : '' }}">
        <label for="">Field 2</label>
        {{ Form::text('field_2', $record->field_2, ['class' => 'form-control']) }}
        <span class="help-block">{{ $errors->first('field_2') }}</span>
    </div>

    <div class="form-group {{ $errors->has('field_3') ? 'has-error' : '' }}">
        <label for="">Field 3</label>
        {{ Form::text('field_3', $record->field_1, ['class' => 'form-control']) }}
        <span class="help-block">{{ $errors->first('field_3') }}</span>
    </div>

我不确定在声明消息时错误是否在请求类中,或者如果在视图中,我该如何显示该自定义消息?

1 个答案:

答案 0 :(得分:0)

您可以显示自定义错误消息,例如

public function messages()
{
    return [
        'max' => 'Insert some value.',
   ];
}