Laravel/Livewire v3 数组元素验证时如何设置别名自定义错误提示
Laravel/Livewire v3 数组元素验证时如何设置别名自定义错误提示
我完全懂你现在的卡点——单个字段用as参数就能轻松替换错误提示里的字段名,但轮到数组元素验证时,files.0这种带索引的字段名就直接显示出来了,看着特别不友好。别担心,有两种简单的方法能解决这个问题:
方法一:在#[Validate]注解里直接指定属性别名
你可以在注解里同时配置规则、自定义消息和属性别名,给files.*设置统一的别名file,这样所有数组元素的错误提示都会自动替换成你想要的名称:
#[Validate([ "files" => ["array", "max:5"], "files.*" => ["image", "mimes:jpg,bmp,png"] ], messages: [ "files.*.image" => "The :attribute field must be an image.", "files.*.mimes" => "The :attribute field must be a file of type: png, jpg, bmp." ], attributes: [ "files.*" => "file" ])] public array $files = [];
这里的attributes数组就是用来给字段设置别名的,:attribute占位符会自动替换成你指定的file。
方法二:在组件里定义attributes()方法
如果你的组件里有多个数组字段需要设置别名,或者想把别名配置和规则分开,也可以在组件中单独定义attributes()方法:
#[Validate([ "files" => ["array", "max:5"], "files.*" => ["image", "mimes:jpg,bmp,png"] ])] public array $files = []; public function attributes() { return [ 'files.*' => 'file', // 这里还可以添加其他字段的别名 ]; }
这样Livewire在生成错误提示时,会自动使用你在这里定义的别名替换原字段名。
两种方法都能实现你想要的效果,把原来的The files.0 field must be a file of type: png, jpg.改成The file field must be a file of type: png, jpg.,选哪种就看你的代码结构偏好啦~
备注:内容来源于stack exchange,提问作者Erikas
相关产品推荐
相关产品推荐

