laravel json数组验证
程序员文章站
2022-07-12 15:11:45
...
自定义json数组验证规则
1.php artisan make:rule 名称
2.规则文件内容如下:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;
class JsonArray implements Rule
{
protected $rules;
protected $errorMessage;
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct($rules)
{
$this->rules = $rules;
}
/**
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$list = json_decode($value,true);
if(empty($list)){
$this->errorMessage = 'json数据格式错误';
return false;
}
foreach($list as $item){
$validator = Validator::make($item,$this->rules);
if($validator->fails()){
$this->errorMessage = $validator->errors()->first();
return false;
}
}
return true;
}
/**
* @return array|string
*/
public function message()
{
return 'json详情数据验证失败-'.$this->errorMessage;
}
}
具体用法:
public function rules()
{
return [
'goods_detail' => [
'required',
'json',
new JsonArray([
'goods_sku_id' => 'required|integer|min:1',
'count' => 'required|integer|min:1',
])],
];
}
上一篇: JSON内容
下一篇: Java 取JSON内容