mesak / laravel-opis-validator
Laravel FormRequest 与 Opis Validator
v1.0.2
2022-08-16 09:04 UTC
Requires
- php: ^7.3|^8.0
- illuminate/support: ^8.0|^9.0
- opis/json-schema: ^2.0
README
Laravel FormRequest 与 Opis JSON Schema Validator
使用 Opis JSON Schema 来验证您的 Laravel 表单请求。
安装
composer require mesak/laravel-opis-validator
或者您可以直接将其作为依赖项引用到您的 composer.json
文件中
{ "require": { "mesak/laravel-opis-validator": "^1.0.0" } }
示例
请求
<?php namespace App\Http\Requests; use Mesak\LaravelOpisValidator\JsonSchemaRequest; class JsonSchema extends JsonSchemaRequest { protected $extendValidatorMessage = true; /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ '$schema' => "https://json-schema.fullstack.org.cn/draft-07/schema#", "type" => "object", "title" => "Base Preference", "description" => "Base Preference Setting", "properties" => [ "limit" => [ "type" => "integer", "minimum" => 5, "maximum" => 15, "title" => "limit", "attrs" => [ "placeholder" => "limit (limit)" ] ], "page" => [ "type" => "object", "title" => "Page", "attrs" => [ "placeholder" => "Page ( Page )" ], "properties" => [ "limit" => [ "type" => "integer" ] ] ] ], "additionalProperties" => false, "required" => [ "limit", "page" ] ]; } protected function prepareForValidation() { //clear urlencoded data from request //input integer is not allowed in json schema $intance = $this->getValidatorInstance(); foreach ($intance->getRules() as $key => $rule) { $inputValue = $this->input($key); if ($rule == 'integer' && preg_match('/\d+/', $inputValue)) { $this->merge([ $key => intval($inputValue), ]); } } $intance->setData($this->all()); } }
控制器
use App\Http\Requests\JsonSchema as JsonSchemaRequest; public function update(JsonSchemaRequest $request) { dd($request->validated()); }
使用 Postman 测试您的请求。
curl --location --request POST 'https:///test/update' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data-raw '{
"limit" :10,
"page": {
"limit" : 10
}
}'