【问题标题】:How to get common validation error message for array field如何获取数组字段的常见验证错误消息
【发布时间】:2018-01-15 14:02:27
【问题描述】:

我需要使用图像和标签验证请求。如何为标签返回常见的验证错误消息。

$this->validate($request, [
    'image' => 'required|image,
    'tags.*' => 'string'
]);

当前消息是。

{
    "image": [
        "The image field is required."
    ],
    "tags.0": [
        "The tags.0 must be a string."
    ],
    "tags.1": [
        "The tags.1 must be a string."
    ]
}

预期的消息是。

{
    "image": [
        "The image field is required."
    ],
    "tags": [
        "The tags must be a string."
    ]
}

【问题讨论】:

    标签: laravel validation laravel-5 laravel-validation


    【解决方案1】:

    我认为您应该尝试以下类似的示例:

    public function messages()
            {
                $messages = [];
                foreach ($this->request->get('tags') as $key => $val) {
                    $messages['tags.' . $key . '.string'] = 'The tags must be a string.'
                }
                return $messages;
            } 
    

    希望这对你有用!!!

    【讨论】:

      【解决方案2】:

      你试过了吗,

      $this->validate($request, [
          'image' => 'required|image,
          'tags.*' => 'string'
      ],$messages = [
          'tags.*' => 'The tags must be a string.'
      ]);
      

      我不确定,但这可能对你有用。

      【讨论】:

      • 消息已更改。但它来自多个数组索引。 "tags.0": [ "标签必须是字符串。" ], "tags.1": [ "标签必须是字符串。" ]
      • @noufalcep 这是因为你有多个不正确的数组输入字段字段
      • 是的。我需要多个输入的单个错误消息。
      • @noufalcep 您可以在视图中进行操作。只从消息数组中获取一条消息,但这不是一个好方法
      • 我看不到。我会找到另一个解决方案。
      【解决方案3】:

      您可以将带有* 的消息添加到您的翻译文件as documented

      'custom' => [
          'tags.*' => [
              'string' => 'The tags must be a string.',
          ]
      ],
      

      【讨论】:

      • 消息已更改。但它来自多个数组索引。 "tags.0": [ "标签必须是字符串。" ], "tags.1": [ "标签必须是字符串。" ]
      猜你喜欢
      • 2020-02-13
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多