在 Laravel 9 中,验证索引数组的实现
1、现在的请求参数结构如下所示。准备验证 config[‘appoint_country’][‘appoint_country’][‘value’][0]、config[‘appoint_country’][‘appoint_country’][‘value’][1]。 如图1
{
"title": "自动交运",
"level": 1,
"logistics_channel_id": 474241,
"auto_shipment": 1,
"description": null,
"is_publish": 1,
"config": {
"appoint_country": {
"invert_select": 0,
"value": [
"AD",
"AE"
]
},
"reship_order": {
"value": 0
}
}
}
2、验证代码实现如下,尝试验证索引数组中的值的最大长度为 1。验证失败,符合预期。如图2
$validator = Validator::make(
$request->all(),
[
'config.appoint_country' => 'array',
'config.appoint_country.invert_select' => 'required_with:config.appoint_country|in:0,1',
'config.appoint_country.value' => 'required_with:config.appoint_country|array',
'config.appoint_country.value.*' => 'required_with:config.appoint_country.value.*|max:1',
],
[
'config.appoint_country.array' => '订单目的地为指定国家参数类型错误',
'config.appoint_country.invert_select.required_with' => '是否反选参数为必填',
'config.appoint_country.invert_select.in' => '是否反选参数类型错误',
'config.appoint_country.value.required_with' => '请选择国家',
'config.appoint_country.value.array' => '国家参数类型错误',
]
);
3、为给定属性指定自定义消息。调整如下
$validator = Validator::make(
$request->all(),
[
'config.appoint_country' => 'array',
'config.appoint_country.invert_select' => 'required_with:config.appoint_country|in:0,1',
'config.appoint_country.value' => 'required_with:config.appoint_country|array',
'config.appoint_country.value.*' => 'required_with:config.appoint_country.value.*|max:1',
],
[
'config.appoint_country.array' => '订单目的地为指定国家参数类型错误',
'config.appoint_country.invert_select.required_with' => '是否反选参数为必填',
'config.appoint_country.invert_select.in' => '是否反选参数类型错误',
'config.appoint_country.value.required_with' => '请选择国家',
'config.appoint_country.value.array' => '国家参数类型错误',
'config.appoint_country.value.*.max' => '国家参数类型最大长度是1',
]
);
4、验证失败后,响应自定义的消息。如图3
![现在的请求参数结构如下所示。准备验证 config['appoint_country']['appoint_country']['value'][0]、config['appoint_country']['appoint_country']['value'][1]](https://www.shuijingwanwq.com/wp-content/uploads/2024/03/1-5.png)


近期评论