如何使用 Validator 依据表单字段返回错误?
我们在创建 validator 时会用到 Validator::make($request->all(), [rule], $messages); 这个方法。
关键在于 $messages 这个参数,其使用示例如下:
$messages = [
'same' => 'The :attribute and :other must match.',
'size' => 'The :attribute must be exactly :size.',
'between' => 'The :attribute must be between :min - :max.',
'in' => 'The :attribute must be one of the following types: :values',
];
但是我却想实现这样的:
$messages = [
'title' => '标题填写错误!',
'price' => '价格填写错误!',
'address' => '房屋地址填写错误!',
'content' => '详细描述填写错误!',
];
前一个是 validator 内置的规则字段,而我想实现依据错误的表单字段返回错误,该如何实现?
我需要的是为某个字段(例如“title”)的全部验证属性编写同一个返回信息,有办法统一编写吗?
比如这样:
'title.all' => 'title错误消息'
用来代替title所有属性的错误。
推荐文章: