### Install Micro Dream Form Validate using Composer Source: https://v.itwmw.com/en/6/Guide Instructions for installing the Micro Dream Form Validate extension using Composer, a dependency manager for PHP. This is the primary method for integrating the library into your project. ```shell composer require itwmw/validate ``` -------------------------------- ### Retrieve Item by Key with get() Source: https://v.itwmw.com/en/6/Collection The get method retrieves an item from the collection by its key. If the key does not exist, it returns null or a specified default value, which can also be a callback function for dynamic defaults. It supports dot notation for nested keys and wildcard matching for arrays. ```php $collection = validate_collect(['name' => 'yuyu', 'framework' => 'laravel']); $value = $collection->get('name'); // yuyu ``` ```php $collection = validate_collect(['name' => 'yuyu', 'framework' => 'laravel']); $value = $collection->get('age', 34); // 34 ``` ```php $collection->get('email', function () { return 'yuyu@example.com'; }); // yuyu@example.com ``` ```php $collection = validate_collect([ 'info' => [ 'name' => 'yuyu', 'age' => '88' ] ]); $collection->get('info.name'); // yuyu ``` ```php $collection = validate_collect([ 'info' => [ [ 'name' => 'yuyu', 'age' => '88' ], [ 'name' => 'haha', 'age' => '60' ] ] ]); $collection->get('info.*.name'); /* Array ( [0] => yuyu [1] => haha ) */ ``` -------------------------------- ### Remove Elements from Start of PHP Collection with skip() Source: https://v.itwmw.com/en/6/Collection The `skip()` method returns a new collection with a specified number of elements removed from the beginning. This is a straightforward way to discard initial items. ```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] ``` -------------------------------- ### Take Items from Collection Start or End (PHP) Source: https://v.itwmw.com/en/6/Collection The `take` method returns a new collection containing a specified number of items from either the beginning (positive integer) or the end (negative integer) of the original 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] ``` -------------------------------- ### Configuring Scene Events without Constructor Parameters (PHP) Source: https://v.itwmw.com/en/6/Event Provides an example of setting up a scene event in a validation scenario where the event handler does not require any constructor parameters. The event handler class is directly assigned to the 'event' key. ```php protected $scene = [ 'add' => ['id','user_id','role','event' => CheckPermission::class], ]; ``` -------------------------------- ### Property Retrieval with RuleParamsParser in PHP Source: https://v.itwmw.com/en/6/RuleParamsParser Shows how to retrieve class properties directly within rule definitions using the {->property} syntax. This example uses a 'max' rule that gets its value from the `$passwordMaxSize` property of the current class. It also explains syntax for multi-level and array property access. ```php class Validator extends Validate { use RuleParamsParser; protected int $passwordMaxSize = 18; protected $rule = [ 'password' => 'required|max:{->passwordMaxSize}' ]; } ``` -------------------------------- ### Implementing and Using Processor Interface in PHP Source: https://v.itwmw.com/en/6/Processor Illustrates the creation of a reusable data processor by implementing the `ProcessorInterface`. This processor class can then be directly used for pre- or post-processing. The example demonstrates a `RemoveScriptProcessor` that strips script tags and other HTML. It also shows how to pass constructor arguments to the processor class. ```php class RemoveScriptProcessor implements ProcessorInterface { public function handle($value, string $attribute, array $originalData) { // This is a demo for remove scripts, for display purposes only $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' => 'Name' ]); var_dump($data); //array(1) { // ["name"]=> // string(6) "Name" //} ``` ```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) { // This is a demo for remove scripts, for display purposes only $value = preg_replace('/.*?/si', '', $value); return strip_tags($value, $this->allowTags); } } ``` -------------------------------- ### Define Multiple Processors with Options (PHP) Source: https://v.itwmw.com/en/6/Processor This example shows how to define multiple preprocessors and postprocessors for a single field by utilizing ProcessorOptions::MULTIPLE. It first sets a default value if the field is empty and then applies a trim operation to the field's value. This allows for a sequence of data transformations before or after validation. Dependencies include classes from the Itwmw\Validate\Support\Processor namespace. ```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, ['Default Name', ProcessorExecCond::WHEN_EMPTY], ['trim', ProcessorParams::Value], ] ]; } ``` -------------------------------- ### Size Validation Examples Source: https://v.itwmw.com/en/6/BuiltRule Validates the size of a field. For strings, it's character count; for numbers, an integer value; for arrays, element count; and for files, size in kilobytes. Supports comparing against other fields. ```PHP 'title' => 'size:12' ``` ```PHP 'seats' => 'integer|size:10' ``` ```PHP 'tags' => 'array|size:5' ``` ```PHP 'image' => 'file|size:512' ``` ```PHP Validate::make( [ 'title' => 'string|size:length' ])->check([ 'length' => 5, 'title' => 'title' ]); ``` ```PHP Validate::make( [ 'ids' => 'array|size:length' ])->check([ 'length' => 3, 'ids' => [1,2,3] ]); ``` -------------------------------- ### Get First Matching Element with first() in PHP Source: https://v.itwmw.com/en/6/Collection The first method returns the first element in the collection that satisfies a given truth test. If no callback is provided, it returns the very first element of the collection. 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 ``` -------------------------------- ### nth - PHP: Get every n-th element from collection Source: https://v.itwmw.com/en/6/Collection The `nth` method creates a new collection containing every n-th element from the original collection. An optional starting offset can be provided to begin the selection from a different position. This is useful for sampling data at regular intervals. ```php $collection = validate_collect(['a', 'b', 'c', 'd', 'e', 'f']); $collection->nth(4); // ['a', 'e'] $collection->nth(4, 1); // ['b', 'f'] ``` -------------------------------- ### Regex Validation Example Source: https://v.itwmw.com/en/6/BuiltRule Validates that a field matches a given regular expression. Internally uses PHP's preg_match, requiring proper pattern formatting including delimiters. Supports arrays for specifying rules. ```PHP 'email' => 'regex:/^.+@.+$/i' ``` -------------------------------- ### Environment Variable Usage with RuleParamsParser in PHP Source: https://v.itwmw.com/en/6/RuleParamsParser Demonstrates fetching values from environment variables within rule definitions using the {@env} syntax. This example sets an environment variable `PASSWORD_MAX_SIZE` and uses it in a 'max' rule. This allows for flexible configuration management. ```php putenv('PASSWORD_MAX_SIZE=18'); class Validator extends Validate { use RuleParamsParser; protected int $passwordMaxSize = 18; protected $rule = [ 'password' => 'required|max:{@PASSWORD_MAX_SIZE}' ]; } ``` -------------------------------- ### Method Invocation with RuleParamsParser in PHP Source: https://v.itwmw.com/en/6/RuleParamsParser Illustrates how to invoke methods (global, class, or static) within rule definitions using the {#function} syntax. This example shows a 'max' rule that dynamically fetches its maximum value from a `getPasswordMaxSize` method. It also mentions support for static method calls using fully qualified namespaces. ```php class Validator extends Validate { use RuleParamsParser; protected $rule = [ 'password' => 'required|max:{#getPasswordMaxSize}' ]; public function getPasswordMaxSize(): int { return 18; } } ``` -------------------------------- ### Get Underlying Array from Collection in PHP Source: https://v.itwmw.com/en/6/Collection Demonstrates using the `all()` method to retrieve the original array that backs the collection object. ```PHP validate_collect([1, 2, 3])->all(); // [1, 2, 3] ``` -------------------------------- ### Validating Data with a Custom Validator Class in PHP Source: https://v.itwmw.com/en/6/Validate Shows how to instantiate a custom validator class (e.g., `LoginValidate`) and use its `check` method to validate an array of data. This example demonstrates how validation errors are thrown as `ValidateException` and how successful validation returns the cleaned data. ```php $data = [ 'user' => '123@qq.com', 'pass' => '' ]; $validate = new LoginValidate(); $validate->check($data); // Example of successful validation $data = [ 'user' => '123@qq.com', 'pass' => '123456' ]; $validate = new LoginValidate(); $data = $validate->check($data); ``` -------------------------------- ### Create Sliding Window Views with PHP Collections Source: https://v.itwmw.com/en/6/Collection The `sliding()` method generates chunks representing a sliding window over collection items. It can optionally accept a 'step' argument to define the interval between the start of each chunk. This is useful for processing consecutive items. ```php $collection = validate_collect([1, 2, 3, 4, 5]); $chunks = $collection->sliding(2); $chunks->toArray(); // [[1, 2], [2, 3], [3, 4], [4, 5]] $collection = validate_collect([1, 2, 3, 4, 5]); $chunks = $collection->sliding(3, step: 2); $chunks->toArray(); // [[1, 2, 3], [3, 4, 5]] ``` -------------------------------- ### Implement Castable Interface for Custom Class Casting in PHP Source: https://v.itwmw.com/en/6/Casts Shows how to create a custom caster class that implements the ValidateCastable interface for complex casting logic. The example includes a UserIdCaster class with a static castsAttributes method. ```php use Itwmw\Validate\Support\Concerns\ValidateCastable; class UserIdCaster extends UserId implements ValidateCastable { public static function castsAttributes(string $field, mixed $value, array $attributes): static { // Custom casting logic return new static($value); } } // --- In Validate Class --- protected $casts = ['user_id' => UserIdCaster::class]; ``` -------------------------------- ### Configure Custom Rule Class Paths for Validator Discovery Source: https://v.itwmw.com/en/6/Start To enable the validator to automatically find and use your custom validation rule classes, you need to configure the namespace prefixes. This involves providing the base namespace where your custom rules reside. For example, if your rule's full namespace is 'Itwmw\App\Model\Validate\Rules\AlphaDash', you should set the prefix to 'Itwmw\App\Model\Validate\Rules\'. ```php \Itwmw\Validation\ValidateConfig::instance()->setRulesPath('Itwmw\\App\\Model\\Validate\\Rules\\'); ``` -------------------------------- ### Cast to Decimal Type with Precision in PHP Source: https://v.itwmw.com/en/6/Casts Demonstrates casting to a float with a specified number of decimal places using the 'decimal' cast. The example shows casting to two and four decimal places. ```php protected $casts = [ 'price' => 'decimal:2', // Keep two decimal places 'rate' => 'decimal:4' // Keep four decimal places ]; // '19.99' -> 19.99 // '0.12345' -> 0.1235 ``` -------------------------------- ### Define Processors within Validation Scenes (PHP) Source: https://v.itwmw.com/en/6/Processor This example demonstrates defining pre- and post-processors directly within a validation scene method. The `sceneSave` method configures the 'name' field to receive a default value 'Default Name' when empty and to be trimmed after validation. This approach allows for scene-specific data processing logic. Dependencies include ValidateScene, ProcessorExecCond, and ProcessorParams from the Itwmw\Validate\Support\Processor namespace. ```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', 'Default Name', ProcessorExecCond::WHEN_EMPTY) ->postprocessor('name', 'trim', ProcessorParams::Value); } } $data = Test::make()->scene('save')->check([]); var_dump($data); //array(1) { // ["name"]=> // string(12) "Default Name" //} $data = Test::make()->check([]); var_dump($data); //array(0) { //} ``` -------------------------------- ### Add Additional Conditions to Validation Rules Source: https://v.itwmw.com/en/6/BuiltRule This snippet demonstrates how to add extra conditions to validation rules using the `_except_` keyword. It shows a specific example for a unique email validation, including account ID and record ID considerations. ```php 'email' => 'unique:connection.users,email_address,id,[id],account_id,1' ``` -------------------------------- ### Using Custom Operators in Validation Rules Source: https://v.itwmw.com/en/6/BuiltRule This section explains how to modify the default equality comparison in validation rules by appending custom operators. The example provided shows how to use the 'not equal to' operator (`<>`) to generate a specific SQL WHERE clause. ```php account_id@<>,1 ``` -------------------------------- ### Extract Subsets with PHP Collections slice() Method Source: https://v.itwmw.com/en/6/Collection The `slice()` method extracts a portion of the collection starting at a given index. An optional second argument can limit the size of the returned slice. Keys are preserved by default, but can be reindexed using the `values()` method. ```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] ``` -------------------------------- ### Reset Collection Keys with Values (PHP) Source: https://v.itwmw.com/en/6/Collection The `values` method creates a new collection with all array keys reset to consecutive integers starting from zero. This is helpful for standardizing collection indexes, especially after operations that might alter key order or introduce gaps. ```php $collection = validate_collect([ 10 => ['product' => 'Desk', 'price' => 200], 11 => ['product' => 'Desk', 'price' => 200], ]); $values = $collection->values(); $values->all(); /* [ 0 => ['product' => 'Desk', 'price' => 200], 1 => ['product' => 'Desk', 'price' => 200], ] */ ``` -------------------------------- ### Defining Global Validation Events (PHP) Source: https://v.itwmw.com/en/6/Event Shows how to set up global event handlers that execute before and after the entire validation process. Multiple global event handlers can be specified. ```php protected $event = [ CheckPermission::class => ['owner'] ]; ``` -------------------------------- ### Define Before/After Scene Validation Methods (PHP) Source: https://v.itwmw.com/en/6/Event Demonstrates how to define custom `before` and `after` methods within a validation class for specific scenes, such as 'register'. It shows the basic structure of a validation class extending the base `Validate` class and how to associate custom methods with validation scenes. ```php class LoginValidate extends \Itwmw\Validate\Validate { protected $rule = [ 'name' => 'required|chs', 'user' => 'required|alpha_dash', 'pass' => 'required|min:8', ]; protected $scene = [ 'register' => ['name', 'user', 'pass', 'before' => 'checkRegisterStatus'] ]; public function beforeCheckRegisterStatus(array $data) { return true; } } ``` -------------------------------- ### Find Sole Matching Element in PHP Collections Source: https://v.itwmw.com/en/6/Collection The `sole()` method returns the first element that matches a truth test, but only if exactly one element matches. It can also accept key/value pairs for matching or be called without arguments to get the first element if only one exists. Exceptions are thrown if no match or multiple matches are found. ```php validate_collect([1, 2, 3, 4])->sole(function ($value, $key) { return $value === 2; }); // 2 $collection = validate_collect([ ['product' => 'Desk', 'price' => 200], ['product' => 'Chair', 'price' => 100], ]); $collection->sole('product', 'Chair'); // ['product' => 'Chair', 'price' => 100] $collection = validate_collect([ ['product' => 'Desk', 'price' => 200], ]); $collection->sole(); // ['product' => 'Desk', 'price' => 200] ``` -------------------------------- ### Cast Array or JSON to Collection in PHP Source: https://v.itwmw.com/en/6/Casts Example of casting an array or JSON string to a Collection object using the 'collection' cast. ```php protected $casts = ['users' => 'collection']; ``` -------------------------------- ### Dynamically Setting Validation Scenes in PHP Source: https://v.itwmw.com/en/6/Validate Details the `setScene` method for dynamically defining or overriding validation scenarios. Scenarios allow specifying different sets of validation rules for different contexts (e.g., 'login', 'register'). Passing `null` to `setScene` clears all defined validation scenes, offering dynamic control over validation contexts. ```php // Definition in class protected $scene = [ 'login' => ['user', 'pass'] ]; // Definition of usage methods $v->setScene([ 'login' => ['user', 'pass'] ]); ``` -------------------------------- ### Cast to String Type in PHP Source: https://v.itwmw.com/en/6/Casts Example of casting a validated field to a string type using the 'string' cast in the $casts property. ```php protected $casts = ['zipcode' => 'string']; // 12345 -> '12345' ``` -------------------------------- ### Cast to Float Type in PHP Source: https://v.itwmw.com/en/6/Casts Example of casting a validated field to a float type using the 'float' cast in the $casts property. ```php protected $casts = ['price' => 'float']; // '19.99' -> 19.99 ``` -------------------------------- ### Swap Keys and Values with flip() Source: https://v.itwmw.com/en/6/Collection The flip method creates a new collection by swapping the keys with their corresponding values from the original collection. This is useful when you need to reverse the key-value association. ```php $collection = validate_collect(['name' => 'yuyu', 'age' => '88']); $flipped = $collection->flip(); $flipped->all(); // ['yuyu' => 'name', '88' => 'age'] ``` -------------------------------- ### Cast to Integer Type in PHP Source: https://v.itwmw.com/en/6/Casts Example of casting a validated field to an integer type using the 'int' cast in the $casts property. ```php protected $casts = ['age' => 'int']; // '30' -> 30 ``` -------------------------------- ### Create Collection by Repeating Closure (PHP) Source: https://v.itwmw.com/en/6/Collection The static `times` method generates a new collection by executing a given closure a specified number of times. The closure receives the iteration number as an argument. ```php $collection = Collection::times(10, function ($number) { return $number * 9; }); $collection->all(); // [9, 18, 27, 36, 45, 54, 63, 72, 81, 90] ``` -------------------------------- ### Splice Collection: Limit Size and Remove - PHP Source: https://v.itwmw.com/en/6/Collection Removes and returns a specified number of items from the collection starting at a given index. The original collection is modified. ```php $collection = validate_collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2, 1); $chunk->all(); // [3] $collection->all(); // [1, 2, 4, 5] ``` -------------------------------- ### Defining Scene Events with Constructor Parameters (PHP) Source: https://v.itwmw.com/en/6/Event Demonstrates how to configure scene events within a validation scenario when the event handler requires constructor parameters. The parameters are passed as an array to the 'event' definition. ```php protected $scene = [ 'add' => ['id','user_id','role','event' => [ CheckPermission::class=>[1,2,3,4] ]], ]; ``` -------------------------------- ### Exclude Values with notIn Rule Source: https://v.itwmw.com/en/6/BuiltRule Ensures that the validated field's value is not present in a given list of values. Example: 'type' => 'required|notIn:save,update,delete'. ```php Validate::make([ 'type' => 'required|notIn:save,update,delete' ])->check($data); ``` -------------------------------- ### Create New Collection Instance in PHP Source: https://v.itwmw.com/en/6/Collection Demonstrates creating a new, independent `Collection` instance from an existing one using the `collect()` method. ```PHP $collectionA = validate_collect([1, 2, 3]); $collectionB = $collectionA->collect(); $collectionB->all(); // [1, 2, 3] ``` -------------------------------- ### Splice Collection: Remove and Return from Index - PHP Source: https://v.itwmw.com/en/6/Collection Removes and returns a portion of the collection starting from a specified index. The original collection is modified by removing the spliced elements. ```php $collection = validate_collect([1, 2, 3, 4, 5]); $chunk = $collection->splice(2); $chunk->all(); // [3, 4, 5] $collection->all(); // [1, 2] ``` -------------------------------- ### Create Basic Collections in PHP Source: https://v.itwmw.com/en/6/Collection Shows how to instantiate a new collection object from a simple array using the `validate_collect` helper function. ```PHP $collection = validate_collect([1, 2, 3]); ``` -------------------------------- ### PHP Validation Scenario for List Source: https://v.itwmw.com/en/6/Scene Sets up a validation scenario named 'list' in PHP, specifying which fields should be included in the validation process. This scenario includes 'search.order', 'search.keyword', and 'search.recycle'. ```php protected $scene = [ 'list' => ['search.order','search.keyword','search.recycle'] ]; ``` -------------------------------- ### Get Unique Items with Unique (PHP) Source: https://v.itwmw.com/en/6/Collection The `unique` method filters a collection to keep only unique items. It preserves original keys. For nested data, uniqueness can be determined by a specified key or a custom closure. ```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'], ] */ ``` -------------------------------- ### Count Items in a Collection Source: https://v.itwmw.com/en/6/Collection The `count` method returns the total number of elements present in a collection. This is a straightforward way to get the size of the collection. It does not modify the collection and simply returns an integer representing the count. ```php $collection = validate_collect([1, 2, 3, 4]); $collection->count(); // 4 ``` -------------------------------- ### Create and Manipulate Collections in PHP Source: https://v.itwmw.com/en/6/Collection Demonstrates creating a collection from an array, applying transformations like converting to uppercase, and filtering out empty elements using chained methods. ```PHP $collection = validate_collect(['yuyu', 'abigail', null])->map(function ($name) { return strtoupper($name); })->reject(function ($name) { return empty($name); }); ``` -------------------------------- ### PHP Scene Class: Get Validation Data Source: https://v.itwmw.com/en/6/Scene Describes the 'getData' method of the Scene class in PHP, used to retrieve the current validation data. By default, it returns all validated values. ```php public function getData(string $key = '', $default = null) ``` -------------------------------- ### Get Random Item(s) from Collection - PHP Source: https://v.itwmw.com/en/6/Collection The `random` method returns a random item from the collection. If an integer is provided, it returns a collection of that many random items. If the collection has fewer items than requested, an `InvalidArgumentException` is thrown. ```php $collection = validate_collect([1, 2, 3, 4, 5]); $collection->random(); // 4 - (retrieved randomly) ``` ```php $collection = validate_collect([1, 2, 3, 4, 5]); $random = $collection->random(3); $random->all(); // [2, 4, 5] - (retrieved randomly) ``` -------------------------------- ### Implement Presence Verifier for Database Validation Rules Source: https://v.itwmw.com/en/6/Start When using validation rules that interact with a database, such as 'Exists' and 'Unique', you must implement the PresenceVerifierInterface. This ensures that the validation process can correctly verify the existence or uniqueness of data in your database. After implementing the interface, instantiate your custom verifier and set it using ValidateConfig::instance()->setPresenceVerifier(). ```php class PresenceVerifier implements \Itwmw\Validation\Support\Interfaces\PresenceVerifierInterface {} \Itwmw\Validation\ValidateConfig::instance()->setPresenceVerifier(new PresenceVerifier()); ``` -------------------------------- ### Split Collection into Smaller Chunks in PHP Source: https://v.itwmw.com/en/6/Collection Illustrates how to divide a collection into smaller collections of a specified size using the `chunk()` method. ```PHP $collection = validate_collect([1, 2, 3, 4, 5, 6, 7]); $chunks = $collection->chunk(4); $chunks->all(); // [[1, 2, 3, 4], [5, 6, 7]] ``` -------------------------------- ### Conditionally Skip Validation with exclude_if Rule Source: https://v.itwmw.com/en/6/BuiltRule Demonstrates how to use the `exclude_if` validation rule to prevent validation of certain fields if another field has a specific value. This example shows that `appointment_date` and `doctor_name` are not validated if `has_appointment` is `false`. ```php use Itwmw\Validate\Validate; $validator = Validate::make([ 'has_appointment' => 'required|boolean', 'appointment_date' => 'exclude_if:has_appointment,false|required|date', 'doctor_name' => 'exclude_if:has_appointment,false|required|string', ])->check($data); ``` -------------------------------- ### Pass Parameters to Scene Event Methods (PHP) Source: https://v.itwmw.com/en/6/Event Illustrates how to pass parameters to `before` and `after` event methods within a validation scene. This includes passing specific values or arrays to custom methods, enabling more complex validation logic. ```php protected $message = [ 'user.required' => 'user is required' ]; protected $scene = [ 'register' => ['name', 'user', 'pass', 'before' => 'setDefaultName','after'=> [ 'checkUserExist' => [1,2,3,4] ]] ]; public function afterCheckUserExist(array $data,$a,$b,$c) { return true; } ``` -------------------------------- ### Get Strictly Unique Items with uniqueStrict (PHP) Source: https://v.itwmw.com/en/6/Collection The `uniqueStrict` method functions identically to `unique` but employs strict type comparisons when determining uniqueness. This is crucial when differentiating between types like integers and strings with equivalent numeric values. ```php // Signature is the same as unique, but uses strict comparisons. ``` -------------------------------- ### Extend Collections with Custom Macros in PHP Source: https://v.itwmw.com/en/6/Collection Illustrates how to add custom methods (macros) to the Collection class, such as a `toUpper` method, and then use it on a collection instance. ```PHP use Itwmw\Validation\Support\Collection\Collection; use Illuminate\Support\Str; Collection::macro('toUpper', function () { return $this->map(function ($value) { return Str::upper($value); }); }); $collection = validate_collect(['first', 'second']); $upper = $collection->toUpper(); // ['FIRST', 'SECOND'] ``` -------------------------------- ### Validate Fields Only When Present with sometimes Rule Source: https://v.itwmw.com/en/6/BuiltRule This snippet explains and demonstrates the `sometimes` rule, which ensures that validation checks are performed on a field only if that field exists in the data being validated. The `email` field in this example is only validated if it's present in the `$data` array. ```php $v = Validate::make([ 'email' => 'sometimes|required|email', ])->check($data); ``` -------------------------------- ### Define Pre- and Post-processors in Class Properties (PHP) Source: https://v.itwmw.com/en/6/Processor This snippet demonstrates how to define preprocessor and postprocessor for a specific field within a class that extends the Validate base class. The preprocessor sets a default value when the field is empty, and the postprocessor trims the field's value after validation. Dependencies include classes from the Itwmw\Validate\Support\Processor namespace. ```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' => ['Default Name', ProcessorExecCond::WHEN_EMPTY] ]; protected $postprocessor = [ 'name' => ['trim', ProcessorParams::Value] ]; } ``` -------------------------------- ### Set or Add Values with set() Source: https://v.itwmw.com/en/6/Collection The set method allows you to efficiently set or add values to a collection. It supports nested keys using dot notation, enabling easy manipulation of hierarchical data within the collection. ```php $collection = validate_collect(); $collection->set('name','yuyu'); $collection->set('info.age',50); $collection->all() /* Array ( [name] => yuyu [info] => Array ( [age] => 50 ) ) */ ``` -------------------------------- ### Simple Validation with Data and Error Handling in PHP Source: https://v.itwmw.com/en/6/Validate Demonstrates a straightforward way to define validation rules and messages, then check data against these rules. It includes try-catch blocks to handle validation exceptions, returning validated data on success or an error message on failure. Dependencies include the Itwmw\Validate\Validate class and Itwmw\Validate\Exception\ValidateException. ```php try { $data = Validate::make([ 'user' => 'required|email', 'pass' => 'required|lengthBetween:6,16', ], [ 'user.required' => 'Please enter your username', 'user.email' => 'User name format error', 'pass.required' => 'Please enter your password', 'pass.lengthBetween' => 'Password length is 6~16 bits', ])->check($data); } catch (ValidateException $e) { echo $e->getMessage(); } ``` -------------------------------- ### Use Closures for Scene Event Handling (PHP) Source: https://v.itwmw.com/en/6/Event Shows how to use anonymous functions (closures) directly within scene definitions for `before` and `after` event handling. This is useful for inline validation logic or when a separate method is not necessary. ```php protected function sceneLogin(\Itwmw\Validate\Support\ValidateScene $scene) { $scene->only(['user', 'pass', 'captcha']) ->before(function ($data) { // TODO::Verify that the captcha is correct }) ->after(function ($data) { // TODO::Verify that the account password is correct }); } ``` -------------------------------- ### Use Regex Rule Directly and with Named Patterns - PHP Source: https://v.itwmw.com/en/6/Rule This PHP code demonstrates how to use regular expressions for validation. It shows direct usage of a regex string in the rule definition and how to define named regex patterns in the `$regex` property and reference them using `regex:name`. ```php 'id' => 'regex:/^\d+$/', 'id' => ['regex:/^\d+$/'] class Test extends \Itwmw\Validate\Validate { protected $regex = [ 'number' => '/^\d+$/' ]; protected $rule = [ 'id' => 'regex:number' ]; } ``` -------------------------------- ### PHP Scene Class: Get Validation Data as Collection Source: https://v.itwmw.com/en/6/Scene Explains the 'getValidateData' method of the Scene class in PHP, which retrieves the current validation data but returns it as a `ValidateCollection` instance, offering a different way to access validation data. ```php public function getValidateData(): ValidateCollection ``` -------------------------------- ### Using Class Methods as Processors in PHP Source: https://v.itwmw.com/en/6/Processor Shows how to define a data preprocessor using a method within the current class. The method name convention is `methodNameProcessor`. This approach is suitable when processor logic is tightly coupled with the main class. It details the default parameter order when none are explicitly specified. ```php class Test extends Validate { protected $rule = [ 'name' => 'nullable|string', ]; protected $preprocessor = [ 'name' => 'setDefaultName', ]; protected function setDefaultNameProcessor(mixed $value) { return empty($value) ? 'Default Name' : $value; } } $data = Test::make()->check([]); var_dump($data); //array(1) { // ["name"]=> // string(12) "Default Name" //} ``` -------------------------------- ### Validate Against Regular Expression with not_regex Source: https://v.itwmw.com/en/6/BuiltRule Checks that the validated field does not match a given regular expression pattern. This rule uses PHP's `preg_match` function, so the pattern must include valid delimiters. Example: 'email' => 'not_regex:/^.+$/i'. ```php 'email' => 'not_regex:/^.+$/i' ``` -------------------------------- ### Type Casting for Nested Array Fields in PHP Source: https://v.itwmw.com/en/6/Casts Demonstrates how to apply type casting to nested array fields, including the use of the wildcard '*' for array elements. The example casts the 'id' field within user objects to an integer. ```php class TestValidate extends Validate { protected $rule = [ 'users' => 'array:@list', 'users.*' => 'array:name,id', 'users.*.name' => 'required|string', 'users.*.id' => 'required|int|min:0', ]; protected $casts = [ 'users.*.id' => 'integer', ]; } $data = $v->check([ 'users' => [ ['name' => 'Alice', 'id' => '1'], ['name' => 'Bob', 'id' => '2'], ] ]); // $data['users'][0]['id'] will be (int) 1 // $data['users'][1]['id'] will be (int) 2 ``` -------------------------------- ### Using Closures as Processors in PHP Source: https://v.itwmw.com/en/6/Processor Demonstrates how to use a closure directly as a data preprocessor within a validation scene. This method is useful for inline, specific data transformations. It shows how to access field values, attribute names, and original data within the closure. ```php 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 'Default Name'; } return $value; }, ProcessorParams::Value, ProcessorParams::Attribute, ProcessorParams::OriginalData); } } $data = Test::make()->scene('save')->check([]); var_dump($data); //array(1) { // ["name"]=> // string(12) "Default Name" //} ``` -------------------------------- ### Assigning Scene Events using the event() method (PHP) Source: https://v.itwmw.com/en/6/Event Illustrates how to dynamically assign event handlers to custom validation scenes using the 'event' method. This method can be chained to assign multiple handlers and can accept parameters for the handler's constructor. ```php /* * @method event(string $handler,...$params) */ $scene->event(CheckPermission::class) $scene->event(CheckPermission::class,1,2,3)->event(CheckName::class) ``` -------------------------------- ### Pipe Collection into New Instance - PHP Source: https://v.itwmw.com/en/6/Collection The `pipeInto` method creates a new instance of a specified class and passes the collection into its constructor. This is useful for hydrating custom collection classes or objects with collection data. It requires the target class name as an argument. ```php class ResourceCollection { /** * The Collection instance. */ public $collection; /** * Create a new ResourceCollection instance. * * @param Collection $collection * @return void */ public function __construct(Collection $collection) { $this->collection = $collection; } } $collection = validate_collect([1, 2, 3]); $resource = $collection->pipeInto(ResourceCollection::class); $resource->collection->all(); // [1, 2, 3] ``` -------------------------------- ### Skip Elements Until Condition Met in PHP Collections Source: https://v.itwmw.com/en/6/Collection The `skipUntil()` method removes items from the start of a collection until a given callback returns true or a specific value is found. It then returns the remaining items. If the condition is never met, an empty collection is returned. ```php $collection = validate_collect([1, 2, 3, 4]); $subset = $collection->skipUntil(function ($item) { return $item >= 3; }); $subset->all(); // [3, 4] $collection = validate_collect([1, 2, 3, 4]); $subset = $collection->skipUntil(3); $subset->all(); // [3, 4] ``` -------------------------------- ### Paginate Collection Items with forPage() Source: https://v.itwmw.com/en/6/Collection The forPage method returns a new collection containing items for a specific page. It requires the page number and the number of items per page as arguments, allowing for easy pagination of collection data. ```php $collection = validate_collect([1, 2, 3, 4, 5, 6, 7, 8, 9]); $chunk = $collection->forPage(2, 3); $chunk->all(); // [4, 5, 6] ``` -------------------------------- ### min - PHP: Get minimum value from collection Source: https://v.itwmw.com/en/6/Collection The `min` method returns the smallest value from a collection. It can target a specific key for nested arrays or operate directly on a collection of scalar values. If no key is specified, it assumes the collection contains scalar values. ```php $min = validate_collect([['foo' => 10], ['foo' => 20]])->min('foo'); // 10 $min = validate_collect([1, 2, 3, 4, 5])->min(); // 1 ``` -------------------------------- ### max - PHP: Get maximum value from collection Source: https://v.itwmw.com/en/6/Collection The `max` method returns the highest value from a collection. It can operate on a specific key within nested arrays or directly on a collection of scalar values. If no key is provided, it assumes the collection contains scalar values. ```php $max = validate_collect([ ['foo' => 10], ['foo' => 20] ])->max('foo'); // 20 $max = validate_collect([1, 2, 3, 4, 5])->max(); // 5 ``` -------------------------------- ### Take Items Until Condition Met (PHP) Source: https://v.itwmw.com/en/6/Collection The `takeUntil` method retrieves items from a collection until a given callback returns `true` or a specified value is encountered. If the condition is never met, the entire collection is returned. ```php $collection = validate_collect([1, 2, 3, 4]); $subset = $collection->takeUntil(function ($item) { return $item >= 3; }); $subset->all(); // [1, 2] ``` ```php $collection = validate_collect([1, 2, 3, 4]); $subset = $collection->takeUntil(3); $subset->all(); // [1, 2] ``` -------------------------------- ### Get the Last Collection Item Passing a Truth Test or the Last Item Source: https://v.itwmw.com/en/6/Collection The `last` method retrieves the final item in a collection that satisfies a given condition defined by a callback. If no callback is provided, it returns the very last item in the collection. It returns `null` if the collection is empty. ```php validate_collect([1, 2, 3, 4])->last(function ($value, $key) { return $value < 3; }); // 2 validate_collect([1, 2, 3, 4])->last(); // 4 ```