Skip to content

Instantly share code, notes, and snippets.

@sberdyug
Forked from forecho/Model.php
Created July 15, 2022 11:23
Show Gist options
  • Save sberdyug/018bf2231f6d2511627110342759ec06 to your computer and use it in GitHub Desktop.
Save sberdyug/018bf2231f6d2511627110342759ec06 to your computer and use it in GitHub Desktop.
Yii 2 表单验证JSON 二维数据
/**k
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'subtitle'], 'string', 'max' => 100],
['productInfo', 'vaildateProductInfo'], // 自定义验证
['skus', 'vaildateSkus'], // 自定义验证
];
}
// 验证商品详情
public function vaildateProductInfo($attribute)
{
$this->vaildateBasic(new ProductInfoForm(), $attribute, $this->scenario);
}
// 验证商品SKU
public function vaildateSkus($attribute)
{
$this->vaildateBasic(new SkusForm(), $attribute, $this->scenario);
}
{
"product_category_id": 1318,
"product_kind_ids": "476",
"name": "圣诗哲中老年男士衬衫短袖衬中年男 短袖 全棉 衬蓝色印花衬衣夏",
"subtitle": "sdsdsd",
"keyword": "中老年,男士,爸爸,夏季,时尚",
"product_no": null,
"show_price": 12,
"prod_weight": "0.00",
"hits": 0,
"sales": null,
"status": 1,
"sort": 1,
"show_sale_num": 1,
"productInfo": {
"detail_pic": "1",
"description": "23",
"detail": "a"
},
"skus": [
{
"sku_no": "B-320140",
"name": "sd",
"reserves": 100,
"freez_reserve": 0,
"market_price": "0.00",
"cost_price": "0.00",
"retail_price": "99.00",
"sales": 0,
"status": 0,
"createdtime": "0000-00-00 00:00:00",
"is_custom": -1,
"postage": null,
"kind_ids": "476,460",
"kind_value_ids": "477,478"
},
{
"sku_no": "B-320139",
"name": "sdsd",
"reserves": 100,
"freez_reserve": 0,
"market_price": "0.00",
"cost_price": "0.00",
"retail_price": "99.00",
"sales": 0,
"status": 0,
"createdtime": "0000-00-00 00:00:00",
"is_custom": -1,
"postage": null,
"kind_ids": "476,460",
"kind_value_ids": "477,478"
}
]
}
/**
* model校验
* @param $model
* @param $attribute string 需要校验的内容
* @param string $scenario
*/
public function vaildateBasic($model, $attribute, $scenario = '')
{
if (!$this->hasErrors()) {
// 判断是否是二维数组
if (count($this->$attribute) == count($this->$attribute, 1)) {
$this->vaildateForm($model, $this->$attribute, $scenario);
} else {
foreach ($this->$attribute as $key => $value) {
$this->vaildateForm($model, $value, $scenario);
}
}
}
}
public function vaildateForm($model, $attribute, $scenario = '')
{
if (is_array($attribute)) {
$model = new $model;
// 添加场景
if ($scenario) {
$model->scenario = $scenario;
}
$function = new \ReflectionClass($model);
$model->load([$function->getShortName() => $attribute]);
$model->validate();
if ($model->firstErrors) {
$this->addErrors($model->firstErrors);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment