【问题标题】:Laravel nested array validation messageLaravel 嵌套数组验证消息
【发布时间】:2019-04-15 16:06:21
【问题描述】:

我有一个需要验证的嵌套 json 数组。我正在尝试为数组中的字段提供自定义验证消息。我浏览了文档和一些帖子,但我仍然无法弄清楚。我指定的规则是:

    return [
        'member_id'                 => 'required|exists:member,id',
        'payment_method'            => 'required',
        'items.*.products.*.id'       => 'required|exists:product,id',
        'items.*.products.*.quantity' => 'required|integer|min:1',
        'items.*.packages.*.id'       => 'required|exists:package,id',
        'items.*.packages.*.quantity' => 'required|integer|min:1'
    ];

在我的消息功能中

   public function messages(){
        return [
            'custom' => [
                'items.*.products.*.id' => [
                    'required'  => 'Product ID is required.',
                    'exists' => 'Selected product invalid.',
                ],
            ],
        ];
   }

但是我的验证信息仍然是: The selected items.0.products.0.id is invalid.

【问题讨论】:

    标签: laravel validation


    【解决方案1】:

    您可以只定义自定义属性名称,而不是大量自定义消息!

    public function attributes()
    {
        return [
            'items.*.products.*.id' => 'product',
            'items.*.products.*.quantity' => 'product quantity',
            'items.*.packages.*.id' => 'package',
            'items.*.packages.*.quantity' => 'package quantity',
        ];
    }
    

    您的验证消息将是:The selected product is invalid.

    见:https://laravel.com/docs/5.8/validation#customizing-the-validation-attributes

    【讨论】:

      【解决方案2】:

      试试这个:

         public function messages(){
              return [
                  'items.*.products.*.id.required' => 'your message here',
                  'items.*.products.*.id.exists' => 'your message here',
                  'items.*.products.*.id.exists' => 'your message here',
                  'items.*.products.*.quantity.required' => 'your message here',
                  'items.*.products.*.quantity.integer' => 'your message here',
                  'items.*.products.*.quantity.min' => 'your message here',
                  // etc... you get the idea
              ];
         }
      

      见:https://laravel.com/docs/5.7/validation#custom-error-messages 为给定属性指定自定义消息

      【讨论】:

        【解决方案3】:

        您是否尝试过像这样不使用custom 键:

        public function messages(){
            return [
                 'items.*.products.*.id' => [
                        'required'  => 'Product ID is required.',
                        'exists'    => 'Selected product invalid.',
                 ]
            ];
        }
        

        【讨论】:

          猜你喜欢
          • 2016-03-27
          • 2017-10-28
          • 1970-01-01
          • 2016-08-21
          • 2013-08-01
          • 2017-04-22
          • 2019-07-25
          • 2014-05-18
          • 2017-11-19
          相关资源
          最近更新 更多