Laravel 5.7:用于表单验证的自定义属性不起作用

时间:2019-05-10 14:18:31

标签: laravel laravel-5.7

我想使用自定义消息和属性来验证表单。例如,用户应该看到name: The name may not be greater than 20 characters.而不是Name: Please use less characters.

我正在使用AJAX以及Laravel返回的response.data.errors对象的键和值。我正在使用Laravel 5.7。

这是我的validatorRegisterController函数的简化版本。

protected function validator(array $data)
{
    // Nice attribute names
    $attributes = [
        'name' => 'Name',
        // ...
    ];

    // Custom messages
    $messages =  [
        'max' => 'Please use less characters.'
        // ...
    ];

    // Rules
    $rules = [
        'name'=> 'required|max:20',
        // ...
    ];

    // Working for messages, but not for attribute names
    $validator = Validator::make($data, $rules, $messages, $attributes);

    // Also not working
    // $validator->setAttributeNames($attributes);

    return $validator;
}

出现验证错误时,用户会收到诸如name: Please use less characters.之类的消息。这意味着将显示来自我的自定义数组的消息,但使用默认属性名称。怎么了?

4 个答案:

答案 0 :(得分:1)

属性不会替换键名,它们用于更改消息中键的外观(即this),以实现您要在问题中尝试做的事情,您需要创建一个新的数据数组。

The Name field is required

答案 1 :(得分:0)

这来自位于resources / Lang / xx /

中的validation.php

编辑:

您必须使用

$messages = [ 'name.max' => 'Your sentence here', ];

答案 2 :(得分:0)

您必须向所有验证规则发送消息。

// Custom messages
$messages =  [
    'name.required' => 'The name field is required',
    'name.max:20' => 'Please use less characters.'
    // ...
];

答案 3 :(得分:0)

使用Laravel Form Request,向下滚动到Customizing The Error Messages部分。查看下面的示例代码。

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserRegistrationForm extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required|max:20',
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'name.max' => 'Please use less characters'
        ];
    }
}

在控制器中

public function register(UserRegistrationForm $request)
    {
         // do saving here
    }