【问题标题】:Laravel 5.7: Custom attributes for form validation not workingLaravel 5.7:表单验证的自定义属性不起作用
【发布时间】:2019-09-28 11:26:20
【问题描述】:

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

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

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

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

    // Custom messages
    $messages =  [
        'max' => 'Please use fewer 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 fewer characters. 的消息。这意味着显示来自我的自定义数组的消息,但使用默认属性名称。这里有什么问题?

【问题讨论】:

  • 语法挑剔:“请使用 less 牛奶”(不可数),“请使用 更少 个字符”(可数)。
  • 谢谢!不敢相信我居然写了“更少的字符”……

标签: laravel laravel-5.7


【解决方案1】:

属性不会替换键名,它们用于更改消息中键的外观 - 即The Name field is required - 以实现您在问题中尝试执行的操作,您需要创建一个新数据数组。


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

    // ...

    Validator::make($data, $rules, $messages);
}

【讨论】:

  • 谢谢,我没想到会这样。您的解决方案运行良好。我预计我必须在 create 方法 ('name' => $data['Name']) 中反转整个事情,但事实并非如此。
【解决方案2】:

使用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
    }

【讨论】:

    【解决方案3】:

    这来自位于 resources/Lang/xx/ 中的 validation.php

    编辑:

    你必须使用

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

    【讨论】:

    • 你对 messages 有误:如果你想为 max 规则的所有验证显示相同的消息,像 'max' => 'Your sentence here' 这样的东西很好。但无论如何,我的问题与 属性 有关。
    • 我写的是 'name.max' 而不是 'max' 一个人
    • 我知道这一点。我的目的是通知您您的答案是错误的:我确实不必必须使用name.max
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 2020-12-10
    • 2022-01-25
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多