### Install微梦表单验证 using Composer Source: https://v.itwmw.com/6/Guide.html This snippet shows how to install the 微梦表单验证 extension using Composer. It requires the Composer package manager to be installed. ```bash composer require itwmw/validate ``` -------------------------------- ### Doesn't Start With 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段是否不以给定的任意值开头。 ```PHP doesnt_start_with:_foo_ ,_bar_ ,... ``` -------------------------------- ### Define and Use a Basic Processor Class (PHP) Source: https://v.itwmw.com/6/Processor.html Demonstrates how to define a processor class that implements the ProcessorInterface and how to integrate it into a validation class. The example shows a processor that removes script tags and strips HTML tags from a value. ```php class RemoveScriptProcessor implements ProcessorInterface { public function handle($value, string $attribute, array $originalData) { // 处理script demo,仅供展示 $value = preg_replace('/.*?/si', '', $value); return strip_tags($value); } } class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $postprocessor = [ 'name' => RemoveScriptProcessor::class, ]; } $data = Test::make()->check([ 'name' => '名称' ]); var_dump($data); //array(1) { // ["name"]=> // string(6) "名称" //} ``` -------------------------------- ### Starts With Validation Rule Source: https://v.itwmw.com/6/BuiltRule.html Validates that a field begins with one of the provided values. ```PHP starts_with:_foo_,_bar_,... ``` -------------------------------- ### Skip Elements from Start of Collection using skip() Source: https://v.itwmw.com/6/Collection.html The `skip` method returns a new collection containing all elements except for the specified number of elements from the beginning. It takes the number of elements to skip as an argument. ```php $collection = validate_collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $collection = $collection->skip(4); $collection->all(); // [5, 6, 7, 8, 9, 10] ``` -------------------------------- ### Get the First Item or Matching Item in a Collection (PHP) Source: https://v.itwmw.com/6/Collection.html The `first` method returns the first item in the collection. If a callback is provided, it returns the first item that passes the test implemented by the callback. If the collection is empty, `null` is returned. ```PHP validate_collect([1, 2, 3, 4])->first(function ($value, $key) { return $value > 2; }); // 3 ``` ```PHP validate_collect([1, 2, 3, 4])->first(); // 1 ``` -------------------------------- ### Create New Collection with Every Nth Element using nth() Source: https://v.itwmw.com/6/Collection.html The nth method creates a new collection containing every nth element from the original collection. An optional offset can be provided as the second argument to specify the starting position. ```php $collection = validate_collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->nth(4); // ['a', 'e'] $collection->nth(4, 1); // ['b', 'f'] ``` -------------------------------- ### slice() Source: https://v.itwmw.com/6/Collection.html Returns a slice of the collection starting at the given index. ```APIDOC ## GET /collection/slice ### Description Returns a slice of the collection starting at the given index. An optional length can be specified to limit the number of elements returned. ### Method GET ### Endpoint /collection/slice ### Parameters #### Query Parameters - **start** (integer) - Required - The starting index of the slice. - **length** (integer) - Optional - The number of elements to return. ### Request Example ```json { "start": 4, "length": 2 } ``` ### Response #### Success Response (200) - **collection** (object) - The sliced collection. #### Response Example ```json { "collection": [ 5, 6 ] } ``` ``` -------------------------------- ### 通过方法设置验证场景 (PHP) Source: https://v.itwmw.com/6/Validate.html 使用 `setScene()` 方法可以动态设置或叠加验证场景。传入 `null` 会清空所有已定义的验证场景。 ```php // 类中定义 protected $scene = [ 'login' => ['user', 'pass'] ]; // 使用方法定义 $v->setScene([ 'login' => ['user', 'pass'] ]); ``` -------------------------------- ### Get Value by Key with Defaults - PHP Source: https://v.itwmw.com/6/Collection.html The `get` method retrieves the value associated with a given key. If the key does not exist, it returns `null` or a specified default value. A default value can also be a callback function, returning its result if the key is not found. Dot notation is supported for accessing nested data, and the wildcard '*' can be used to match multiple array elements. ```php $collection = validate_collect(['name' => 'yuyu', 'age' => '88']); $value = $collection->get('name'); // yuyu $value = $collection->get('sex', 1); // 1 $collection->get('email', function () { return 'yuyu@example.com'; }); // yuyu@example.com $collection = validate_collect([ 'info' => [ 'name' => 'yuyu', 'age' => '88' ] ]); $collection->get('info.name'); // yuyu $collection = validate_collect([ 'info' => [ [ 'name' => 'yuyu', 'age' => '88' ], [ 'name' => 'haha', 'age' => '60' ] ] ]); $collection->get('info.*.name'); /* Array ( [0] => yuyu [1] => haha ) */ ``` -------------------------------- ### 使用多个处理器 (PHP) Source: https://v.itwmw.com/6/Processor.html 通过 `ProcessorOptions::MULTIPLE` 声明,可以为同一个字段定义多个处理器。处理器将按顺序依次执行,允许进行链式数据处理。 ```php use Itwmw\Validate\Support\Processor\ProcessorExecCond; use Itwmw\Validate\Support\Processor\ProcessorOptions; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => [ ProcessorOptions::MULTIPLE, ['默认名称', ProcessorExecCond::WHEN_EMPTY], ['trim', ProcessorParams::Value], ] ]; } ``` -------------------------------- ### Define a Processor Class with Constructor Arguments (PHP) Source: https://v.itwmw.com/6/Processor.html Illustrates how to create a processor class that accepts arguments through its constructor. This allows for more flexible and configurable data processing, as shown with the `allowTags` parameter for `strip_tags`. ```php class RemoveScriptProcessor implements ProcessorInterface { protected array $allowTags; public function __construct(string $allowTags = '') { $this->allowTags = explode(',', $allowTags); } public function handle($value, string $attribute, array $originalData) { // 处理script demo,仅供展示 $value = preg_replace('/.*?/si', '', $value); return strip_tags($value, $this->allowTags); } } ``` -------------------------------- ### Get strictly unique items from a collection Source: https://v.itwmw.com/6/Collection.html The `uniqueStrict` method functions identically to `unique`, but it performs strict type and value comparisons when determining uniqueness. ```PHP $collection = validate_collect([1, '1', 2, 2, 3, 4, '2']); $uniqueStrict = $collection->uniqueStrict(); $uniqueStrict->values()->all(); // [1, "1", 2, 3, 4, "2"] ``` -------------------------------- ### Proceed to Next Scene with next() Source: https://v.itwmw.com/6/Scene.html The `next` method is used to proceed to the next scene or scene selector. It takes the name of the next scene as a string argument. ```php public function next(string $name): static // $name: The name of the next scene or scene selector. ``` -------------------------------- ### Get Minimum Value with min() Source: https://v.itwmw.com/6/Collection.html The min method returns the minimum value for a given key in the collection. If no key is specified, it returns the minimum value of the collection itself. ```php $min = validate_collect([['foo' => 10], ['foo' => 20]])->min('foo'); // 10 $min = validate_collect([1, 2, 3, 4, 5])->min(); // 1 ``` -------------------------------- ### Get All Keys from Collection (PHP) Source: https://v.itwmw.com/6/Collection.html The `keys` method returns a new collection containing all the keys from the original collection. This is useful for iterating over or accessing keys independently. ```PHP $collection = validate_collect([ 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ]); $keys = $collection->keys(); $keys->all(); // ['prod-100', 'prod-200'] ``` -------------------------------- ### 执行场景关联验证 (PHP) Source: https://v.itwmw.com/6/Scene.html 演示了如何使用场景关联进行验证。调用 `User::make()->scene('register')->check()` 会首先验证 'register' 场景的字段,如果成功,则继续验证 'checkUserInfo' 场景的字段。最终返回所有验证通过的数据。 ```php $data = User::make()->scene('register')->check([ 'username' => 'Melody', 'password' => '123456', 'mobile' => '13122223333', 'name' => 'Melody', 'age' => '20' ]); print_r($data); ``` -------------------------------- ### Get Validator Collection with getValidateData() Source: https://v.itwmw.com/6/Scene.html The `getValidateData` method retrieves the currently validated data, similar to `getData`. However, this method returns a `ValidateCollection` class instance, providing a collection of validators. ```php public function getValidateData(): ValidateCollection ``` -------------------------------- ### Custom Rule with Constructor Parameters (PHP) Source: https://v.itwmw.com/6/Rule.html Shows how to create custom validation rules that accept parameters. These parameters are passed to the rule's constructor, allowing for dynamic rule configuration. ```php class Length extends BaseRule { protected $message = ':attribute的长度不符合要求'; protected $size; public function __construct(int $size) { $this->size = $size; } public function passes($attribute, $value): bool { return strlen($value) === $this->size; } } ``` -------------------------------- ### Convert a collection to a PHP array Source: https://v.itwmw.com/6/Collection.html The `toArray` method converts the collection into a PHP array. It also converts nested `Arrayable` instances and collections into arrays. Use `all` to get the original array. ```PHP $collection = validate_collect(['name' => 'Desk', 'price' => 200]); $collection->toArray(); /* [ ['name' => 'Desk', 'price' => 200], ] */ ``` -------------------------------- ### 定义预处理器和后处理器属性 (PHP) Source: https://v.itwmw.com/6/Processor.html 通过 `$preprocessor` 和 `$postprocessor` 属性为验证器定义前置和后置数据处理器。可以指定处理器的执行条件,例如在字段为空时执行。 ```php use Itwmw\Validate\Support\Processor\ProcessorExecCond; use Itwmw\Validate\Support\Processor\ProcessorOptions; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => ['默认名称', ProcessorExecCond::WHEN_EMPTY] ]; protected $postprocessor = [ 'name' => ['trim', ProcessorParams::Value] ]; } ``` -------------------------------- ### Declined If 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 当另一个字段等于指定值时,当前字段必须为 'no', 'off', 0, 或 false。 ```PHP declined_if:_anotherfield_,_value_ ,... ``` -------------------------------- ### Get Mode Value with mode() Source: https://v.itwmw.com/6/Collection.html The mode method returns the most frequent value for a given key in the collection. If no key is specified, it returns the mode of the collection itself. The result is always returned as an array. ```php $mode = validate_collect([ ['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40] ])->mode('foo'); // [10] $mode = validate_collect([1, 1, 2, 4])->mode(); // [1] ``` -------------------------------- ### Get unique items from a collection Source: https://v.itwmw.com/6/Collection.html The `unique` method returns all unique items from the collection. It can accept a key to determine uniqueness in nested structures or a callback function. It uses loose comparison by default. ```PHP $collection = validate_collect([1, 1, 2, 2, 3, 4, 2]); $unique = $collection->unique(); $unique->values()->all(); // [1, 2, 3, 4] ``` ```PHP $collection = validate_collect([ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], ]); $unique = $collection->unique('brand'); $unique->values()->all(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ] */ ``` ```PHP $unique = $collection->unique(function ($item) { return $item['brand'].$item['type']; }); $unique->values()->all(); /* [ ['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'], ['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'], ['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'], ['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'], ] */ ``` -------------------------------- ### 简单验证与异常处理 (PHP) Source: https://v.itwmw.com/6/Validate.html 使用 `Validate::make()` 方法进行简单数据验证,并捕获 `ValidateException` 异常以处理验证失败的情况。成功时返回验证后的数据,失败时抛出异常。 ```php try { $data = Validate::make([ 'user' => 'required|email', 'pass' => 'required|lengthBetween:6,16', ], [ 'user.required' => '请输入用户名', 'user.email' => '用户名格式错误', 'pass.required' => '请输入密码', 'pass.lengthBetween' => '密码长度为6~16位', ])->check($data); } catch (ValidateException $e) { echo $e->getMessage(); } ``` -------------------------------- ### 场景关联定义 (PHP) Source: https://v.itwmw.com/6/Scene.html 定义了一个 User 验证器,其中 'register' 场景关联了 'checkUserInfo' 场景。当 'register' 场景验证通过后,会继续执行 'checkUserInfo' 场景的验证。这种方式允许按顺序验证不同的字段集。 ```php class User extends Validate { protected $rule = [ 'username' => 'required|alpha', 'password' => 'required|alpha_num|min:6|max:16', 'mobile' => 'regex:/^1[3-9]\d{9}$/', 'name' => 'alpha|max:10', 'age' => 'numeric|min:1|max:150' ]; protected $scene = [ 'register' => ['username', 'password', 'mobile', 'next' => 'checkUserInfo'], 'checkUserInfo' => ['name', 'age'] ]; } ``` -------------------------------- ### Handle Scene Events with event() Source: https://v.itwmw.com/6/Scene.html The `event` method allows you to specify handler classes for scene events. A scene can utilize multiple event handler classes. It takes the handler's namespace and optional parameters for the middleware build method. ```php public function event(string $handler, ...$params): static // $handler: Processor namespace, can be passed with :class // $params: Parameters passed to the middleware build method, unlimited quantity ``` -------------------------------- ### 在验证场景中使用数据处理器 (PHP) Source: https://v.itwmw.com/6/Processor.html 可以在验证场景类中通过 `preprocessor` 和 `postprocessor` 方法定义数据处理器。这允许为不同的验证场景配置不同的数据处理逻辑。 ```php use Itwmw\Validate\Support\Processor\ProcessorExecCond; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; use Itwmw\Validate\ValidateScene; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected function sceneSave(ValidateScene $scene): void { $scene->only(true) ->preprocessor('name', '默认名称', ProcessorExecCond::WHEN_EMPTY) ->postprocessor('name', 'trim', ProcessorParams::Value); } } $data = Test::make()->scene('save')->check([]); var_dump($data); $data = Test::make()->check([]); var_dump($data); ``` -------------------------------- ### Get Median Value from Collection (PHP) Source: https://v.itwmw.com/6/Collection.html The `median` method calculates the median value of a collection. It can compute the median of the entire collection or for a specific key across all items. The median is the middle value in a sorted list of numbers. ```PHP $median = validate_collect([ ['foo' => 10], ['foo' => 10], ['foo' => 20], ['foo' => 40] ])->median('foo'); // 15 $median = validate_collect([1, 1, 2, 4])->median(); // 1.5 ``` -------------------------------- ### Get Last Element or Matching Element (PHP) Source: https://v.itwmw.com/6/Collection.html The `last` method retrieves the last element of a collection. It can also accept a callback to find the last element that satisfies a given condition. If the collection is empty, it returns null. ```PHP validate_collect([1, 2, 3, 4])->last(function ($value, $key) { return $value < 3; }); // 2 validate_collect([1, 2, 3, 4])->last(); // 4 ``` -------------------------------- ### Before Or Equal 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段的值对应的日期必须在给定日期之前或与之相同。日期通过 `strtotime` 函数处理。 ```PHP before_or_equal:_date_ ``` -------------------------------- ### Slice Collection using slice() Source: https://v.itwmw.com/6/Collection.html The `slice` method returns a portion of the collection starting from a given index. An optional second parameter can limit the number of elements returned. By default, original keys are preserved; use `values()` to re-index. ```php $collection = validate_collect([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); $slice = $collection->slice(4); $slice->all(); // [5, 6, 7, 8, 9, 10] $slice = $collection->slice(4, 2); $slice->all(); // [5, 6] ``` -------------------------------- ### 定义字段后置数据处理器 (PHP) Source: https://v.itwmw.com/6/Validate.html 使用 `$postprocessor` 属性可以为字段定义后置数据处理器。这允许在验证规则应用之后对数据进行处理,例如去除字符串两端的空格。 ```php protected $postprocessor = [ 'name' => ['trim', ProcessorExecCond::WHEN_NOT_EMPTY, ProcessorParams::Value] ]; ``` -------------------------------- ### Accepted 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段是否为 'yes', 'on', 1, 或 true。常用于服务条款接受等字段。 ```PHP accepted ``` -------------------------------- ### 定义字段前置数据处理器 (PHP) Source: https://v.itwmw.com/6/Validate.html 通过 `$preprocessor` 属性可以为特定字段定义前置数据处理器。这允许在验证规则应用之前对数据进行预处理,例如设置默认值。 ```php protected $preprocessor = [ 'name' => ['默认名称', ProcessorExecCond::WHEN_EMPTY] ]; ``` -------------------------------- ### Create a collection using a callback Source: https://v.itwmw.com/6/Collection.html The static `times` method creates a new collection by invoking a callback function a specified number of times. The callback receives the iteration number. ```PHP $collection = Collection::times(10, function ($number) { return $number * 9; }); $collection->all(); // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90] ``` -------------------------------- ### Remove and Return Slice of Collection (PHP) Source: https://v.itwmw.com/6/Collection.html The `splice()` method removes and returns a segment of the collection starting from a specified index. An optional second argument limits the number of removed elements, and a third argument allows replacing removed elements with new ones. ```php $collection = validate_collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2); $chunk->all(); // [3, 4, 5] $collection->all(); // [1, 2] ``` ```php $collection = validate_collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2, 1); $chunk->all(); // [3] $collection->all(); // [1, 2, 4, 5] ``` ```php $collection = validate_collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2, 1, [10, 11]); $chunk->all(); // [3] $collection->all(); // [1, 2, 10, 11, 4, 5] ``` -------------------------------- ### Different 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段值必须与另一个指定字段的值不同。 ```PHP different:_field_ ``` -------------------------------- ### Get Maximum Value from Collection (PHP) Source: https://v.itwmw.com/6/Collection.html The `max` method returns the maximum value from a collection. It can operate on the collection's values directly or by specifying a key to find the maximum value of that specific key across all items. If the collection is empty, it returns null. ```PHP $max = validate_collect([ ['foo' => 10], ['foo' => 20] ])->max('foo'); // 20 $max = validate_collect([1, 2, 3, 4, 5])->max(); // 5 ``` -------------------------------- ### 定义预定义正则表达式规则 (PHP) Source: https://v.itwmw.com/6/Validate.html 使用 `$regex` 属性可以预定义正则表达式,并在验证规则中引用它们。这有助于复用和管理常用的正则表达式。 ```php protected $regex = [ 'number' => '/^\d+$/' ]; ``` -------------------------------- ### Get Random Value(s) from Collection using random() Source: https://v.itwmw.com/6/Collection.html The `random` method retrieves a random value from the collection. Optionally, you can pass an integer to specify the number of random values to retrieve, returning a new collection. If the requested number of items exceeds the collection size, an `InvalidArgumentException` is thrown. ```php $collection = validate_collect([1, 2, 3, 4, 5]); $collection->random(); // 4 - (retrieved randomly) $random = $collection->random(3); $random->all(); // [2, 4, 5] - (retrieved randomly) ``` -------------------------------- ### Accepted If 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 当另一个字段等于指定值时,当前字段必须为 'yes', 'on', 1, 或 true。 ```PHP accepted_if:anotherfield,value,... ``` -------------------------------- ### Before 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段的值对应的日期必须在给定的日期之前。日期可直接提供或引用另一个字段。日期通过 `strtotime` 函数处理。 ```PHP before:_date_ ``` -------------------------------- ### Configure Field Preprocessor with preprocessor() Source: https://v.itwmw.com/6/Scene.html The `preprocessor` method sets or cancels a pre-processor for a specific field. It accepts the field name, a callback (which can be a value, function name, current class method, processor class, or closure), and optional execution parameters. ```php public function preprocessor(string $field, callable|Closure|mixed|null|ProcessorInterface $callback, ProcessorSupport ...$params): static // $field: Field name. // $callback: Value, function name, current class's handler method name, handler class, closure, etc. // $params: Execution parameters. ``` -------------------------------- ### Using Regex for Validation (PHP) Source: https://v.itwmw.com/6/Rule.html Demonstrates how to use regular expressions directly for validation. For regex patterns containing the '|' symbol, it's necessary to define the rule using an array. ```php 'id' => 'regex:/^\d+$/', ``` ```php 'id' => ['regex:/^\d+$/'] ``` -------------------------------- ### Dimensions 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证文件是否为图片并符合指定的尺寸比例。支持 min_width, max_width, min_height, max_height, width, height, 和 ratio。 ```PHP 'avatar' => 'dimensions:min_width=100,min_height=200' 'avatar' => 'dimensions:ratio=3/2' ``` -------------------------------- ### Add Pre-Validation Callback with before() Source: https://v.itwmw.com/6/Scene.html The `before` method adds a callback function to be executed before validation begins. The callback must be a method within the current class or a closure. It receives the pre-validation data as an array as its first argument. ```php public function before(callable|Closure|string $callbackName, ...$params): static // $callbackName: Method name within the current class (without prefix), or a closure. The first argument passed to the closure is an array of pre-validation data. // $params: Parameters to be passed to the method. ``` -------------------------------- ### 执行场景复用验证 (PHP) Source: https://v.itwmw.com/6/Scene.html 实例化验证器并调用 `scene('save')->check($data)` 来执行 'save' 场景。由于 'save' 场景通过 `next` 关键字复用了 'edit' 场景,因此验证将基于 'edit' 场景的规则进行。 ```php $validate = new ArticleValidate(); $validate->scene('save')->check($data); ``` -------------------------------- ### 配置自定义验证规则路径 Source: https://v.itwmw.com/6/Rule.html 在使用自定义验证规则前,需要配置自定义规则的命名空间前缀。建议在Provider中进行设置,以确保验证器能够找到自定义规则类。 ```php ValidateConfig::instance()->setRulesPath('Itwmw\App\Model\Validate\Rules\'); ``` -------------------------------- ### take() Source: https://v.itwmw.com/6/Collection.html The take method returns a new collection containing the specified number of elements. It can also accept a negative integer to take elements from the end of the collection. ```APIDOC ## take() ### Description Returns a new collection containing the specified number of elements. A negative integer can be passed to retrieve elements from the end of the collection. ### Method `take(int $limit): static` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Taking the first 3 elements $collection = validate_collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(3); $chunk->all(); // Taking the last 2 elements $collection = validate_collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(-2); $chunk->all(); ``` ### Response #### Success Response (200) `static`: A new collection containing the specified elements. #### Response Example ```php // Example 1 output [0, 1, 2] // Example 2 output [4, 5] ``` ``` -------------------------------- ### 独立调用自定义规则对象 Source: https://v.itwmw.com/6/Rule.html 自定义规则对象可以独立于验证器进行调用。通过`make()`方法创建规则实例,然后调用`check()`方法进行验证。 ```php Chs::make()->check("名字"); ``` -------------------------------- ### 使用验证场景进行数据验证 (PHP) Source: https://v.itwmw.com/6/Scene.html 演示了如何实例化一个验证器,并使用 `scene()` 方法指定要应用的验证场景(例如 'add' 场景),然后调用 `check()` 方法来验证输入数据。如果验证通过,`check()` 方法会返回经过验证的数据。 ```php $data = [ 'content' => '内容', 'title' => '这是一个标题' ]; $validate = new ArticleValidate(); $data = $validate->scene('add')->check($data); ``` -------------------------------- ### Prepend Item to Collection with prepend() Source: https://v.itwmw.com/6/Collection.html The prepend method adds an item to the beginning of the collection. An optional second argument can specify the key for the new item. ```php $collection = validate_collect([1, 2, 3, 4, 5]); $collection->prepend(0); $collection->all(); // [0, 1, 2, 3, 4, 5] $collection = validate_collect(['one' => 1, 'two' => 2]); $collection->prepend(0, 'zero'); $collection->all(); // ['zero' => 0, 'one' => 1, 'two' => 2] ``` -------------------------------- ### 环境变量示例 - 规则参数解析器 Source: https://v.itwmw.com/6/RuleParamsParser.html 演示如何使用 `{@env}` 语法在规则定义中获取环境变量的值。需要在运行前通过 `putenv()` 函数设置环境变量。 ```php putenv('PASSWORD_MAX_SIZE=18'); class Validator extends Validate { use RuleParamsParser; protected int $passwordMaxSize = 18; protected $rule = [ 'password' => 'required|max:{@PASSWORD_MAX_SIZE}' ]; } ``` -------------------------------- ### After Or Equal 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段的值对应的日期必须在给定日期之后或与之相同。日期通过 `strtotime` 函数处理。 ```PHP after_or_equal:_date_ ``` -------------------------------- ### 为特定规则定义自定义异常 (PHP) Source: https://v.itwmw.com/6/Validate.html 通过 `$exceptions` 属性可以为特定字段或特定规则的验证失败指定抛出自定义异常类。这提供了更细粒度的异常处理机制。 ```php protected $rule = [ 'name' => 'required' ]; protected $exceptions = [ TestException::class => 'name.required' ]; // 多个字段或规则 protected $rule = [ 'name' => 'required|integer', 'age' => 'required|integer' ]; protected $exceptions = [ TestException::class => [ 'name', 'age.required' ] ]; // 为所有规则指定异常 protected $rule = [ 'name' => 'required|integer', 'age' => 'required|integer' ]; protected $exceptions = TestException::class; ``` -------------------------------- ### Partition Collection with partition() Source: https://v.itwmw.com/6/Collection.html The partition method splits the collection into two based on a callback's return value (true or false). It returns an array containing two collections: one for items that passed the condition and one for items that did not. ```php $collection = validate_collect([1, 2, 3, 4, 5, 6]); list($underThree, $equalOrAboveThree) = $collection->partition(function ($i) { return $i < 3; }); $underThree->all(); // [1, 2] $equalOrAboveThree->all(); // [3, 4, 5, 6] ``` -------------------------------- ### After 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段是否为给定日期之后的值。日期可直接提供或引用另一个字段。日期通过 `strtotime` 函数处理。 ```PHP 'start_date' => 'required|date|after:tomorrow' 'finish_date' => 'required|date|after:start_date' ``` -------------------------------- ### 使用自定义验证器进行数据验证 (PHP) Source: https://v.itwmw.com/6/Validate.html 实例化自定义验证器类(如 `LoginValidate`),然后调用 `check()` 方法传入待验证数据。验证失败时会抛出 `ValidateException` 异常,成功时返回验证后的数据。 ```php $data = [ 'user' => '123@qq.com', 'pass' => '' ]; $validate = new LoginValidate(); $validate->check($data); // 验证成功示例 $data = [ 'user' => '123@qq.com', 'pass' => '123456' ]; $validate = new LoginValidate(); $data = $validate->check($data); ``` -------------------------------- ### 通过方法设置错误消息 (PHP) Source: https://v.itwmw.com/6/Validate.html 可以使用 `setMessages()` 方法动态设置或叠加错误消息。此方法支持叠加,传入 `null` 则会清空所有自定义错误消息。 ```php // 类中定义 protected $message = [ 'user.required' => '账号必须填写' ]; // 使用方法定义 $v->setMessages([ 'user.required' => '账号必须填写' ]); ``` -------------------------------- ### 使用闭包作为数据处理器 (PHP) Source: https://v.itwmw.com/6/Processor.html 在验证场景中,可以直接传递一个闭包作为处理器。闭包可以接收 `ProcessorParams` 定义的参数,实现灵活的数据处理逻辑。 ```php use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; use Itwmw\Validate\ValidateScene; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected function sceneSave(ValidateScene $scene): void { $scene->only(true) ->preprocessor('name', function (mixed $value, string $attribute, array $data) { if (empty($value)) { return '默认名称'; } return $value; }, ProcessorParams::Value, ProcessorParams::Attribute, ProcessorParams::OriginalData); } } $data = Test::make()->scene('save')->check([]); var_dump($data); ``` -------------------------------- ### Array 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段是否为有效的 PHP 数组。可使用 '@list' 参数验证数字索引数组,或指定允许的键名,可选键名可用方括号括起。 ```PHP 'ids' => 'array:@list' Validate::make( [ 'user' => 'array:username,locale', ])->check($input); 'user' => 'array:username,locale,[admin]' ``` -------------------------------- ### 使用类方法作为数据处理器 (PHP) Source: https://v.itwmw.com/6/Processor.html 可以在当前类中定义一个方法,并将其命名规则为 `首字母小写的方法名 + Processor`,作为数据处理器。此示例展示了如何使用 `setDefaultNameProcessor` 来设置默认名称。 ```php use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => 'setDefaultName', ]; protected function setDefaultNameProcessor(mixed $value) { return empty($value) ? '默认名称' : $value; } } $data = Test::make()->check([]); var_dump($data); ``` -------------------------------- ### 配置自定义规则路径 (PHP) Source: https://v.itwmw.com/6/Start.html 为了让验证器能够自动发现并使用自定义的验证规则,需要配置自定义规则类的命名空间前缀。此代码示例展示了如何使用 `ValidateConfig::instance()->setRulesPath()` 方法来设置自定义规则的路径。 ```php use Itwmw\Validation\Support\Facades\ValidateConfig; // 假设你的自定义规则类完整命名空间是 Itwmw\App\Model\Validate\Rules\AlphaDash ValidateConfig::instance()->setRulesPath('Itwmw\App\Model\Validate\Rules\'); ``` -------------------------------- ### 场景验证前方法定义 (PHP) Source: https://v.itwmw.com/6/Event.html 在自定义验证场景中,使用`before`方法定义一个在场景验证前执行的回调函数或方法。该方法接收验证数据作为参数。 ```php protected $scene = [ 'register' => ['name', 'user', 'pass', 'before' => 'checkRegisterStatus'] ]; public function beforeCheckRegisterStatus(array $data) { return true; } ``` -------------------------------- ### Date Format 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段是否匹配给定的日期格式。应与 'date' 规则二选一使用。 ```PHP date_format:_format_ ``` -------------------------------- ### Between 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段的大小(字符串、数字、数组、文件)必须在给定的最小值和最大值之间。 ```PHP between:_min_ ,_max_ ``` -------------------------------- ### 规则类中格式化错误消息 - 使用类属性 %{字段名} Source: https://v.itwmw.com/6/Message.html 说明了如何在自定义验证规则类中,通过 `%{字段名}` 的语法直接在错误消息中使用规则类本身的公共或受保护属性。这种方式无需进行格式转换,可以直接引用属性值,使错误消息更加直观和易于理解。例如,可以直接在消息中使用 `$size` 属性的值。 ```php class Length extends BaseRule { protected $message = ':attribute的长度需为%{size}个字节'; protected $size; public function __construct(int $size) { $this->size = $size; } public function passes($attribute, $value): bool { return strlen($value) === $this->size; } } ``` -------------------------------- ### Confirmed 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段必须具有匹配的 `{field}_confirmation` 字段。例如,password 字段需要 password_confirmation 字段。 ```PHP confirmed ``` -------------------------------- ### skip() Source: https://v.itwmw.com/6/Collection.html Returns a new collection excluding the given number of elements from the beginning. ```APIDOC ## GET /collection/skip ### Description Returns a new collection containing all elements except for the first given number of elements. ### Method GET ### Endpoint /collection/skip ### Parameters #### Query Parameters - **count** (integer) - Required - The number of elements to skip from the beginning. ### Request Example ```json { "count": 4 } ``` ### Response #### Success Response (200) - **collection** (object) - The new collection with elements skipped. #### Response Example ```json { "collection": [ 5, 6, 7, 8, 9, 10 ] } ``` ``` -------------------------------- ### 传递参数给处理器 (PHP) Source: https://v.itwmw.com/6/Processor.html 处理器可以接收参数,除了使用 `ProcessorParams` 常量,还可以直接传递参数。此示例展示了如何使用 `explode` 和 `array_map` 来处理逗号分隔的字符串ID。 ```php use Itwmw\Validate\Support\Processor\ProcessorOptions; use Itwmw\Validate\Support\Processor\ProcessorParams; use Itwmw\Validate\Validate; class Test extends Validate { protected $rule = [ 'id' => 'required|string' ]; protected $postprocessor = [ 'id' => [ ProcessorOptions::MULTIPLE, ['explode', ',', ProcessorParams::Value], ['array_map', 'intval', ProcessorParams::Value], ], ]; } $data = Test::make()->check([ 'id' => '1,2,3,4,5' ]); var_dump($data); ``` -------------------------------- ### 使用extendImplicit方法进行隐式验证 Source: https://v.itwmw.com/6/Rule.html 当需要验证即使属性为空也应执行规则时,可以使用`extendImplicit`方法。这会暗示该属性是必需的,即使它为空字符串或不存在。 ```php $v->extendImplicit('foo', function ($attribute, $value, $parameters, $validator) { return $value == 'foo'; }); ``` -------------------------------- ### 使用extend方法注册全局规则(闭包) Source: https://v.itwmw.com/6/Rule.html 可以通过`extend`方法向验证器注册全局规则。第一个参数是规则名,第二个参数是验证逻辑的闭包,第三个参数是自定义错误消息。 ```php class UserValidator extends Validate { } $v = UserValidator::make(); $v->extend("chs",function ($attribute, $value, $parameters, $validator) { return is_scalar($value) && 1 === preg_match('/^[x{4e00}-x{9fa5}]+$/u', (string)$value); }, ':attribute的值只能具有中文'); ``` -------------------------------- ### reduceWithKeys() Source: https://v.itwmw.com/6/Collection.html Reduces the collection to a single value, passing the key and value to the callback. ```APIDOC ## POST /collection/reduceWithKeys ### Description Reduces the collection to a single value, passing the key and value to the callback function. An initial value can be provided. ### Method POST ### Endpoint /collection/reduceWithKeys ### Parameters #### Request Body - **callback** (callable) - Required - The callback function to execute for each item. - **initial** (any) - Optional - The initial value for the carry. ### Request Example ```json { "callback": "function ($carry, $value, $key) use ($ratio) { return $carry + ($value * $ratio[$key]); }", "initial": 0 } ``` ### Response #### Success Response (200) - **value** (any) - The reduced value. #### Response Example ```json { "value": 4264 } ``` ``` -------------------------------- ### 使用extendReplacer方法定义错误消息 Source: https://v.itwmw.com/6/Rule.html 可以通过`extendReplacer`方法为自定义规则定义更灵活的错误消息。它接受规则名和一个闭包,闭包可以根据验证结果动态生成错误消息。 ```php $v->extendReplacer('chs', function ($message, $attribute, $rule, $parameters) { return '自定义错误消息'; }); ``` ```php $v->extendReplacer('chs', "Rules@chsMessage"); // 如果为静态方法 $v->extendReplacer('chs', [Rules::class, 'chsMessage']); ``` -------------------------------- ### Distinct 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证数组字段是否不包含重复值。支持 'strict' 参数进行严格比较,和 'ignore_case' 参数忽略大小写。 ```PHP 'foo.*.id' => 'distinct' 'foo.*.id' => 'distinct:strict' 'foo.*.id' => 'distinct:ignore_case' ``` -------------------------------- ### 全局事件定义 (PHP) Source: https://v.itwmw.com/6/Event.html 通过`$event`属性定义全局事件处理器。键是事件类名,值是方法的数组,这些方法将在验证器验证前后执行。 ```php protected $event = [ CheckPermission::class => ['owner'] ]; ``` -------------------------------- ### Email 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段是否为有效的电子邮件格式。 ```PHP 'email' => 'email' ``` -------------------------------- ### Enum 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段是否为枚举类型。 ```PHP enum ``` -------------------------------- ### Take a specified number of items from a collection Source: https://v.itwmw.com/6/Collection.html The `take` method returns a new collection containing a specified number of elements. A negative integer can be passed to retrieve elements from the end of the collection. ```PHP $collection = validate_collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(3); $chunk->all(); // [0, 1, 2] ``` ```PHP $collection = validate_collect([0, 1, 2, 3, 4, 5]); $chunk = $collection->take(-2); $chunk->all(); // [4, 5] ``` -------------------------------- ### Ends With 验证规则 (PHP) Source: https://v.itwmw.com/6/BuiltRule.html 验证字段是否以给定的值之一结尾。 ```PHP ends_with:_foo_ ,_bar_ ,... ``` -------------------------------- ### 定义全局事件处理器 (PHP) Source: https://v.itwmw.com/6/Validate.html 通过 `$event` 属性可以为验证器定义全局事件。这允许在验证流程的特定点执行自定义逻辑,例如在验证开始或结束时。 ```php protected $event = [ CheckSiteStatus::class ]; ```