需求
在使用 laravel backpack table 组件时,需要对几个自定义规格字段做校验。例如:
- 名称、销售价格、成本价为必填
- 价格确认为数字
而这个是用 laravel 自带的校验规则无法满足的。
自定义校验规则
新建一个 Rule Objects
php artisan make:rule SpecFieldRequired
此时,会发现多了一个文件 app/Rules/SpecFieldRequired.php
模拟的输入数据
local.INFO: [{"name":"1斤装","price":"50","cost_price":"40","original_price":"60"},{"name":"2斤装","price":"100"},{"name":"3斤装","price":"150","cost_price":"120","original_price":"180"}]
local.INFO: [{"name":"1斤装","price":"50","cost_price":"40","original_price":"60"},{"name":"2斤装","price":"100"},{"name":"","price":"150","cost_price":"120","original_price":"180"}]
local.INFO: [{"name":"1斤装","price":"50","cost_price":"40","original_price":"60"},{"name":"2斤装","price":"100"},{"name":"","price":"150","cost_price":"120","original_price":"180"},{"price":"11"}]
app/Rules/SpecFieldRequired.php
public function passes($attribute, $value)
{
$specs = json_decode($value);
foreach ($specs as $spec) {
if (array_key_exists('price', $spec)) {
if (!is_numeric($spec->price)) {
return false;
}
} else {
return false;
}
if (array_key_exists('name', $spec)) {
if (!trim($spec->name)) {
return false;
}
} else {
return false;
}
if (array_key_exists('cost_price', $spec)) {
if (!is_numeric($spec->cost_price)) {
return false;
}
} else {
return false;
}
}
return true;
}
public function message()
{
return '规格设置不正确!请确认规格名称、价格及成本价设置正确。';
}
app/Http/Requests/ProductRequest.php
use App\Rules\SpecFieldRequired;
public function rules()
{
return [
'specifications' => ['required', new SpecFieldRequired],
];
}
用户体验更好的一种方式
我一直觉得校验是最后一道防线,但不是最好的体验。最好的体验应该是直观地告诉用户,让用户明白哪些是需要注意的。所以,增加提示信息是必要的。
'columns' => [
'name' => '名称 (必填)',
'price' => '销售价格(元) (必填)',
'cost_price' => '成本价 (必填)',
'original_price' => '原价 (选填)',
],
"hint" => "提示:1. 请至少添加一个默认规格。2. 名称,销售价格,成本价为必填项;原价为选填。",
Laravel 数据校验系列
参考
https://laravel.com/docs/5.5/validation#custom-validation-rules
微信关注我哦 👍
我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式