【发布时间】:2019-12-22 03:25:35
【问题描述】:
我正在尝试验证一个字段数组,我想指出验证错误中哪个字段有误。
我有一个表格可以上传多张图片。对于每个图像,HTML 必须有一个 caption 和 alt 属性。如果我尝试上传 3 张图片并错过了其中两张的字段,我会收到如下错误消息:
The field 'image file' is required.
The field 'image caption' is required.
The field 'image alt' is required.
The field 'image caption' is required.
The field 'image alt' is required.
The field 'image file' is required.
问题是:attribute 重复了,如果用户想要更新多张图片,他/她必须检查所有图片以查找缺少哪个字段!
我想要的是这个:
The field 'image file (item 1)' is required.
The field 'image caption (item 1)' is required.
The field 'image alt (item 1)' is required.
The field 'image caption (item 3)' is required.
The field 'image alt (item 3)' is required.
The field 'image file (item 1)' is required.
这样用户就可以知道在哪里解决问题。
首先,我尝试了这个:
$attributes = [
'img.*.file' => 'Image file (item :* )',
'img.*.alt' => 'Image alt (item :* )',
'img.*.caption' => 'Image caption (item :* )',
];
//
$this->validate($request, $rules, [], $attributes);
我认为:* 将被字段的索引(1、2、3、4 等)替换,就像:attribute 被属性替换一样。但是,:* 不会被字段的索引替换;相反,它显示为纯文本。
值得注意的是,我设计代码的方式是,HTML 名称属性按顺序为所有字段(img[1][alt]、[img][2][alt] 等、img[1][caption]、[img][2][caption] 等)编制索引,所以每个字段具有正确的索引。考虑到这一点,我想有一种方法可以获取索引并用于在错误消息中创建自定义属性。
我搜索了这个问题,在这里Validation on fields using index position找到了同样的问题,但是它使用了angular,而不是laravel。
如何获取索引并将其放在attribute 中?如果不可能,是否有任何其他方法可以在无需设置错误消息的情况下实现理想的结果?
我想更改 attributes 并保留 laravel 提供的默认错误消息
【问题讨论】:
标签: laravel validation