### Install Validator Example Packages (Bash) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/undisclosed-password.md Installs all required packages for the command-line example, including HTTP clients, factories, and the validator itself. ```bash $ composer require \ php-http/message \ php-http/message-factory \ php-http/discovery \ php-http/curl-client \ laminas/laminas-diactoros \ laminas/laminas-validator ``` -------------------------------- ### Regex Validator Example (Laminas) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Demonstrates how the Regex validator now requires the 'pattern' option during construction. Previously, this could be set after instantiation, but this practice has been removed to ensure valid states. ```php use Laminas\Validator\Regex; // Previous behavior (deprecated): // $validator = new Regex(); // $validator->setPattern('/^[a-zA-Z]+$/'); // Current behavior: $validator = new Regex(['pattern' => '/^[a-zA-Z]+$/']); if ($validator->isValid('example')) { // Valid } else { // Invalid } ``` -------------------------------- ### Install Laminas Uri Component Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/uri.md Installs the laminas-uri package, which is a dependency for the default URI handler used by Laminas\Validator\Uri. ```bash composer require laminas/laminas-uri ``` -------------------------------- ### Install Laminas Validator Digits Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/digits.md Installs the laminas-filter component, a dependency for LaminasValidatorDigits. ```bash composer require laminas/laminas-filter ``` -------------------------------- ### Install laminas-i18n for message translation Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/intro.md This command installs the laminas-i18n component, which is required for translating validator messages. ```bash $ composer require laminas/laminas-i18n ``` -------------------------------- ### Replacing LessThan Validator with NumberComparison Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md This example shows the migration path from the legacy LessThan validator to the new NumberComparison validator. The parameters are adjusted to match the new validator's API for inclusive comparisons. ```php $validator = new Laminas\Validator\LessThan([ 'max' => 10, 'inclusive' => true, ]); ``` ```php $validator = new Laminas\Validator\NumberComparison([ 'max' => 10, 'inclusiveMax' => true, ]); ``` -------------------------------- ### Install laminas-db Component Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/db.md Command to install the laminas-db component using Composer, which is a prerequisite for using the Db validators. ```bash composer require laminas/laminas-db ``` -------------------------------- ### Install laminas-validator using Composer Source: https://github.com/laminas/laminas-validator/blob/3.9.x/README.md This command installs the laminas-validator library using Composer, the dependency manager for PHP. ```bash composer require laminas/laminas-validator ``` -------------------------------- ### Install Laminas Servicemanager Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validator-chains.md Installs the laminas-servicemanager component, which is a dependency for validator chains. ```bash composer require laminas/laminas-servicemanager ``` -------------------------------- ### Install Validator Dependencies (Bash) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/undisclosed-password.md Installs the necessary HTTP client and factory components required by the UndisclosedPassword validator. ```bash $ composer require psr/http-client $ composer require psr/http-factory ``` -------------------------------- ### Install Laminas URI for Sitemap Loc Validation Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/sitemap.md Shows the Composer command to install the laminas-uri component, which is a dependency for the Laminas\Validator\Sitemap\Loc validator. ```bash $ composer require laminas/laminas-uri ``` -------------------------------- ### Install i18n Resources (Bash) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/messages.md Command to install the laminas-i18n-resources package, which provides pre-translated validation messages for multiple languages. ```bash $ composer require laminas/laminas-i18n-resources ``` -------------------------------- ### LaminasValidatorFileCrc32 Usage Examples Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/crc32.md Demonstrates how to instantiate and use the Crc32 validator with single or multiple hash values, and how to perform validation on a file. ```php require 'vendor/autoload.php'; use Laminas\Validator\File\Crc32; // Does file have the given hash? $validator = new Crc32('3b3652f'); // Or, check file against multiple hashes $validator = new Crc32(['3b3652f', 'e612b69']); // Perform validation with file path if ($validator->isValid('./myfile.txt')) { // file is valid } else { // file is invalid // print_r($validator->getMessages()); } ``` -------------------------------- ### Laminas Validator Step Floating-Point Usage Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/step.md Illustrates how to use the Laminas Validator Step with floating-point numbers for base and step values. This example shows validation against a sequence starting at 1.1 with a step of 2.2. ```php $validator = new Laminas\Validator\Step([ 'baseValue' => 1.1, 'step' => 2.2, ]); echo $validator->isValid(1.1); // prints true echo $validator->isValid(3.3); // prints true echo $validator->isValid(3.35); // prints false echo $validator->isValid(2.2); // prints false ``` -------------------------------- ### LaminasValidatorBitwise Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Details changes to the LaminasValidatorBitwise class, including removed methods and behavior changes related to integer input. ```APIDOC ## Laminas\Validator\Bitwise ### Description Changes to the `Laminas\Validator\Bitwise` class, including the removal of `setControl`, `getControl`, `setOperator`, `getOperator`, `setStrict`, `getStrict` methods. The constructor now only accepts an associative array of documented options, and validation will fail if the input is not integer-like. ### Method N/A (Class documentation) ### Endpoint N/A (Class documentation) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Behavior Changes - The constructor now only accepts an associative array of documented options. - Validation will now fail if the input is not `interger-ish` (i.e., `int` or `int-string`). ``` -------------------------------- ### LaminasValidatorCallback Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Details changes to the LaminasValidatorCallback class, including removed methods and the addition of a 'bind' option for scope manipulation. ```APIDOC ## Laminas\Validator\Callback ### Description Changes to the `Laminas\Validator\Callback` class, including the removal of `setCallback`, `getCallback`, `setCallbackOptions`, `getCallbackOptions` methods. A new `bind` option has been added to bind the callback to the validator's scope, allowing error message manipulation. The signature for user-supplied callables is now consistently `callable(mixed $value, array $context, ...$userDefinedParameters)`. ### Method N/A (Class documentation) ### Endpoint N/A (Class documentation) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### New Option - `bind`: Binds the given callback to the scope of the validator, allowing manipulation of error messages from within the callback. ``` -------------------------------- ### Basic Usage of Laminas File Hash Validator Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/hash.md Demonstrates how to initialize and use the LaminasValidatorFileHash validator to check if a file's content matches a specific hash or a list of hashes using a specified algorithm. Includes examples of direct instantiation and option array usage. ```php use Laminas\Validator\File\Hash; // Does file have the given hash? $validator = new Hash('3b3652f', 'crc32'); // Or, check file against multiple hashes $validator = new Hash(['3b3652f', 'e612b69'], 'crc32'); // Or use options notation: $validator = new Hash([ 'hash' => ['3b3652f', 'e612b69'], 'algorithm' => 'crc32', ]); // Perform validation with file path if ($validator->isValid('./myfile.txt')) { // file is valid } ``` -------------------------------- ### LaminasValidatorBarcode Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Details changes to the LaminasValidatorBarcode class, including removed methods, constructor changes, and adapter interface updates. ```APIDOC ## Laminas\Validator\Barcode ### Description Changes to the `Laminas\Validator\Barcode` class, including the removal of `getAdapter`, `setAdapter`, `getChecksum`, `useChecksum` methods. The constructor now strictly accepts an associative array of documented options, and the `adapter` option can be a Fully Qualified Class Name (FQCN). ### Method N/A (Class documentation) ### Endpoint N/A (Class documentation) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ### Significant Changes to Adapters All shipped barcode adapters no longer extend `AbstractAdapter`. Instead, they implement `Laminas\Validator\Barcode\AdapterInterface`, which specifies only 4 methods: `hasValidLength`, `hasValidCharacters`, `hasValidChecksum`, and `getLength`. ``` -------------------------------- ### Barcode Adapter Interface (Laminas) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Shows the methods defined in the LaminasValidatorBarcodeAdapterInterface. Adapters no longer extend an abstract class but must implement these four methods for barcode validation. ```php namespace Laminas\Validator\Barcode; interface AdapterInterface { public function hasValidLength(string $value): bool; public function hasValidCharacters(string $value): bool; public function hasValidChecksum(string $value): bool; public function getLength(): int; } ``` -------------------------------- ### Create Custom Barcode Adapter (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/barcode.md Provides an example of creating a custom barcode validator by extending LaminasValidatorBarcodeAbstractAdapter. It defines length, characters, and checksum logic for a new barcode type. ```php isValid($input)) { // input appears to be valid } else { // input is invalid } ?> ``` -------------------------------- ### Laminas Validator Step Basic Usage Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/step.md Demonstrates the basic instantiation and usage of the Laminas Validator Step for integer values. It checks if a given integer is a valid step value starting from 0 with a step of 1. ```php $validator = new Laminas\Validator\Step(); if ($validator->isValid(1)) { // value is a valid step value } else { // false } ``` -------------------------------- ### Laminas Validator Factory Implementation Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/writing-validators.md Provides an example of a factory class for a Laminas validator. The factory utilizes a dependency injection container to resolve services and instantiate the validator with the necessary dependencies and options. ```php final class FlightNumberFactory { public function __invoke(ContainerInterface $container, string $name, array $options = []): FlightNumber { return new FlightNumber( $container->get(FlightNumberValidationService::class), $options, ); } } ``` -------------------------------- ### Combined Hostname Type Validation in PHP Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/hostname.md Illustrates how to combine different hostname validation types using bitwise OR with Laminas\Validator\Hostname constants. This example allows both DNS and IP addresses. ```php use Laminas\Validator\Hostname; $validator = new Hostname([ 'allow' => Hostname::ALLOW_DNS | Hostname::ALLOW_IP, ]); ``` -------------------------------- ### Get Hashes from Laminas File Hash Validator Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/hash.md Shows how to retrieve the array of hashes that the LaminasValidatorFileHash validator is configured to test against. ```php getHash() : array ``` -------------------------------- ### Laminas Validator File Md5 Public Methods Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/md5.md Provides examples of using the public methods getMd5, addMd5, and setMd5 for managing the MD5 hashes against which a file is validated. ```php getMd5() : array ``` ```php addMd5(string|array $options) : void ``` ```php setMd5(string|array $options) : void ``` -------------------------------- ### Specify Database Schema for Validation (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/db.md Example demonstrating how to specify a database schema (e.g., 'my') when performing validation, useful for databases like PostgreSQL. ```php $validator = new Laminas\Validator\Db\RecordExists([ 'table' => 'users', 'schema' => 'my', 'field' => 'id', ]); ``` -------------------------------- ### Handle String Encoding with Laminas StringLength Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/string-length.md This example shows how to specify the encoding of a string for validation. It highlights the behavior when the encoding is explicitly set, especially when it differs from the system's default. ```php $validator = new Laminas\Validator\StringLength(['min' => 6]); $validator->isValid("Ärger"); // returns true $validator = new Laminas\Validator\StringLength(['min' => 6, 'encoding' => 'ascii']); $validator->isValid("Ärger"); // returns false ``` -------------------------------- ### Laminas File WordCount Basic Usage (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/word-count.md Demonstrates basic usage of the Laminas File WordCount validator. It shows how to instantiate the validator with a maximum word count, a range of word counts, and using the options notation. The example also includes how to perform the validation against a file path. ```php use Laminas\Validator\File\WordCount; // Limit the amount of words to a maximum of 2000: $validator = new WordCount(2000); // Limit the amount of words to between 100 and 5000: $validator = new WordCount(100, 5000); // ... or use options notation: $validator = new WordCount([ 'min' => 1000, 'max' => 5000, ]); // Perform validation with file path if ($validator->isValid('./myfile.txt')) { // file is valid } ``` -------------------------------- ### Using Laminas Validator File Hash with SHA256 Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Demonstrates how to instantiate and use the `LaminasValidatorFileHash` validator with the SHA256 algorithm. This replaces the need for specific inheritor classes like `Sha1` or `Md5`. ```php $hash = new \Laminas\Validator\File\Hash([ 'hash' => 'SomeExpectedSha256Hash', 'algorithm' => 'sha256', ]); $hash->isValid('/path/to/file.md'); ``` -------------------------------- ### Combine Hostname Validation Types in PHP Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/hostname.md Illustrates how to combine different hostname validation types using bitwise OR operations. This example allows both DNS and IP address hostnames to be validated. ```php 5]); $validator->isValid("Test"); // returns false $validator->isValid("Testing"); // returns true ``` -------------------------------- ### Limit Both Minimum and Maximum String Length (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/string-length.md Provides an example of setting both minimum and maximum string length constraints simultaneously using the 'min' and 'max' options in LaminasValidatorStringLength for scenarios like username validation. ```php $validator = new Laminas\Validator\StringLength(['min' => 3, 'max' => 30]); $validator->isValid("."); // returns false $validator->isValid("Test"); // returns true $validator->isValid("Testing"); // returns true ``` -------------------------------- ### Removal of Laminasi18n Aliases and Factories Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Details the removal of aliases and factory entries for Laminasi18n validators, which may require enabling the i18n ConfigProvider or Module. ```APIDOC ## General Changes ### Removal of Laminas\i18n Aliases and Factories The [`laminas-i18n`](https://docs.laminas.dev/laminas-i18n/validators/introduction/) component ships a number of validators that historically have been pre-configured from within this component. These aliases and factory entries have been removed. Removal of the aliases here is unlikely to cause any issues, providing you have enabled the `ConfigProvider` or `Module` from `laminas-i18n` in your application. ### Required Options at Construction Time A number of validators now require options during construction now that runtime mutation of validator settings is no longer possible. Validators that require options will now throw an exception when the relevant option is not provided. For example, the [`Regex` validator](#laminasvalidatorregex) requires a `pattern` option. The affected validators are: - `Laminas\Validator\Barcode` - `Laminas\Validator\Bitwise` - `Laminas\Validator\Callback` - `Laminas\Validator\DateComparison` - `Laminas\Validator\Explode` - `Laminas\Validator\InArray` - `Laminas\Validator\IsInstanceOf` - `Laminas\Validator\NumberComparison` - `Laminas\Validator\Regex` - `Laminas\Validator\File\ExcludeExtension` - `Laminas\Validator\File\ExcludeMimeType` - `Laminas\Validator\File\Extension` - `Laminas\Validator\File\FilesSize` - `Laminas\Validator\File\Hash` - `Laminas\Validator\File\ImageSize` - `Laminas\Validator\File\MimeType` - `Laminas\Validator\File\Size` - `Laminas\Validator\File\WordCount` ### General Changes #### Removal of "Getters" and "Setters" In general, most validators no longer have "getters" and "setters" for options and configuration. This forces the provision of valid configuration at construction time. #### Consistent Construction via an Array of Options Validators now primarily accept associative arrays with documented options, rather than a range of constructor arguments. ``` -------------------------------- ### Basic Laminas Validator File Size Usage (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/file/size.md Demonstrates basic usage of the LaminasValidatorFileSize validator to limit file sizes. It shows how to set maximum size in bytes and a range using SI notation (kB, MB). The example also includes how to perform validation on a file path. ```php use Laminas\Validator\File\Size; // Limit the file size to 40000 bytes $validator = new Size(['max' => 40000]); // Limit the file size to between 10kB and 4MB $validator = new Size([ 'min' => '10kB', 'max' => '4MB', ]); // Perform validation with file path if ($validator->isValid('./myfile.txt')) { // file is valid } ``` -------------------------------- ### Transition from LaminasValidatorCsrf to LaminasSessionValidatorCsrf Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md This snippet demonstrates how to update your code to use the new CSRF validator location within the laminas-session component. Ensure 'laminas-session' is listed as a composer dependency. ```php $validator = Laminas\Validator\Csrf::class; ``` ```php $validator = Laminas\Session\Validator\Csrf::class; ``` -------------------------------- ### Limit Maximum String Length with Laminas StringLength Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/string-length.md This example demonstrates how to limit the maximum allowed length of a string using the 'max' option. It checks if the input string's length does not exceed the specified maximum. ```php $validator = new Laminas\Validator\StringLength(['max' => 6]); $validator->isValid("Test"); // returns true $validator->isValid("Testing"); // returns false ``` -------------------------------- ### Configuring NotEmpty Validation Types (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/not-empty.md Shows how to configure the Laminas NotEmpty validator to consider specific types as empty. Examples include validating against the integer 0, the string '0', or both using bitwise operations, arrays of constants, or string names. ```php use Laminas\Validator\NotEmpty; // Returns false on 0 $validator = new NotEmpty(NotEmpty::INTEGER); // Returns false on 0 or '0' $validator = new NotEmpty( NotEmpty::INTEGER | NotEmpty::ZERO); // Returns false on 0 or '0' $validator = new NotEmpty([ NotEmpty::INTEGER, NotEmpty::ZERO ]); // Returns false on 0 or '0' $validator = new NotEmpty(['integer', 'zero']); ``` -------------------------------- ### Configuring NotEmpty Validation Behavior in PHP Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/not-empty.md Illustrates how to configure the NotEmpty validator to consider specific types as empty. It shows examples using integer and zero constants, arrays of constants, and string representations of types. ```php use Laminas\Validator\NotEmpty; // Returns false on 0 $validator = new NotEmpty(['type' => NotEmpty::INTEGER]); // Returns false on 0 or '0' $validator = new NotEmpty(['type' => NotEmpty::INTEGER | NotEmpty::ZERO]); // Returns false on 0 or '0' $validator = new NotEmpty(['type' => [ NotEmpty::INTEGER, NotEmpty::ZERO ]]); // Returns false on 0 or '0' $validator = new NotEmpty(['type' => ['integer', 'zero']]); ``` -------------------------------- ### Refactoring ValidatorChain Fluent Returns (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Demonstrates how to refactor code that uses fluent return values from ValidatorChain methods in version 2 to the void return type in version 3. This involves separating chained method calls into individual statements. ```php // Code making use of fluent return values: $validatorChain->attach(new StringLength()) ->attach(new NotEmpty()) ->attach(new Digits()); // Should be refactored to: $validatorChain->attach(new StringLength()); $validatorChain->attach(new NotEmpty()); $validatorChain->attach(new Digits()); ``` -------------------------------- ### PHP: Check file existence in multiple directories (any) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/file/exists.md This example shows how to use LaminasValidatorFileExists to check if a file exists in any of the specified directories. The 'directory' option takes an array of paths, and setting 'all' to false allows validation if the file is found in at least one directory. ```php use Laminas\Validator\File\Exists; // Allow files that exist in any of the listed directories $validator = new Exists([ 'directory' => ['/tmp', '/var/tmp'], 'all' => false, ]); if ($validator->isValid('myfile.txt')) { // file was found in at least 1 directory } else { // file was not found in one of the directories } ``` -------------------------------- ### PHP: Check file existence in multiple directories (all) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/file/exists.md This example demonstrates using LaminasValidatorFileExists to check if a file exists in all specified directories. The 'directory' option accepts a comma-delimited string, and the 'all' option defaults to true. ```php use Laminas\Validator\File\Exists; // Only allow files that exist in ~both~ directories $validator = new Exists(['directory' => '/tmp,/var/tmp']); if ($validator->isValid('myfile.txt')) { // file is present in all directories } else { // file was not present in at least 1 of the directories } ``` -------------------------------- ### Instantiate ValidatorChain via Plugin Manager (Best Practice) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validator-chains.md Demonstrates the recommended approach for creating ValidatorChain instances by retrieving them from the application's plugin manager. This ensures consistency and proper dependency management. ```php use Psr\Container\ContainerInterface; use Laminas\Validator\NotEmpty; use Laminas\Validator\ValidatorChain; use Laminas\Validator\ValidatorPluginManager; /** @var ContainerInterface $container */ $pluginManager = $container->get(ValidatorPluginManager::class); $chain = $pluginManager->get(ValidatorChain::class); $chain->attach( $pluginManager->get(NotEmpty::class), ); ``` -------------------------------- ### Create Custom Barcode Validation Adapter Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/barcode.md Provides an example of creating a custom barcode validation adapter in PHP that implements LaminasValidatorBarcodeAdapterInterface. This custom adapter validates barcodes with an even number of characters, containing only digits, and includes a placeholder for checksum validation. It then shows how to instantiate the Laminas Barcode validator with this custom adapter. ```php namespace My\Barcode; use Laminas\Validator\Barcode; use Laminas\Validator\Barcode\AdapterInterface; use function ctype_digit; final class CustomBarcodeAdapter implements AdapterInterface { public function hasValidLength(string $value): bool { return strlen($value) % 2 === 0; } public function hasValidCharacters(string $value): bool { return ctype_digit($value); } public function hasValidChecksum(string $value): bool { // Placeholder for actual checksum validation logic return true; } public function getLength(): string { return 'even'; } } // Assuming $input is a string containing the barcode to validate $validator = new Barcode([ 'adapter' => CustomBarcodeAdapter::class, ]); if ($validator->isValid($input)) { // input appears to be valid echo "Custom barcode is valid."; } else { // input is invalid echo "Custom barcode is invalid."; } ``` -------------------------------- ### Bitwise Validator Behavior Change (Laminas) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/migration/v2-to-v3.md Illustrates the stricter type checking for the Bitwise validator. Input must now be an integer or an integer-like string, and previous setter/getter methods for control, operator, and strictness have been removed. ```php use Laminas\Validator\Bitwise; // Previous behavior (deprecated): // $validator = new Bitwise(); // $validator->setOperator(Bitwise::OPERATOR_AND); // Current behavior: $validator = new Bitwise(['operator' => Bitwise::OPERATOR_AND]); // Validation will fail if input is not integer-like // $validator->isValid('abc'); // Throws exception or returns false // Validation will succeed for integer-like input // $validator->isValid(10); // $validator->isValid('10'); ``` -------------------------------- ### Callback Validation with setOptions Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/callback.md Demonstrates setting additional callback options after the validator has been instantiated using the `setOptions` method. ```php class MyClass { public static function myMethod($value, $option) { // some validation return true; } } $valid = new Laminas\Validator\Callback([MyClass::class, 'myMethod']); $options = ['some_option_value']; $valid->setOptions($options); if ($valid->isValid($input)) { // input appears to be valid } else { // input is invalid } ``` -------------------------------- ### Basic Validator Chain Usage (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validator-chains.md Demonstrates creating a ValidatorChain, attaching StringLength and Regex validators, and validating an input string. It also shows how to retrieve error messages. ```php use Laminas\Validator\Regex; use Laminas\Validator\StringLength; use Laminas\Validator\ValidatorChain; // Create a validator chain and add validators to it $validatorChain = new ValidatorChain(); $validatorChain->attach(new StringLength(['min' => 6, 'max' => 12])); $validatorChain->attach(new Regex(['pattern' => '/^[a-z0-9]+$/i'])); // Validate the username if ($validatorChain->isValid($username)) { // username passed validation } else { // username failed validation; print reasons foreach ($validatorChain->getMessages() as $message) { echo "$message\n"; } } ``` -------------------------------- ### Basic Hostname Validation in PHP Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/hostname.md Demonstrates the basic usage of Laminas\Validator\Hostname to validate a hostname. It shows how to instantiate the validator, check validity, and retrieve error messages on failure. ```php $validator = new Laminas\Validator\Hostname(); if ($validator->isValid($hostname)) { // hostname appears to be valid } else { // hostname is invalid; print the reasons foreach ($validator->getMessages() as $message) { echo "$message\n"; } } ``` -------------------------------- ### Check if Username is Not Present in Database (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/db.md Example of using LaminasValidatorDbNoRecordExists to ensure a username is not already in use in the 'users' table. ```php // Check that the username is not present in the database $validator = new Laminas\Validator\Db\NoRecordExists([ 'table' => 'users', 'field' => 'username', 'adapter' => $dbAdapter, ]); if ($validator->isValid($username)) { // username appears to be valid } else { // username is invalid; print the reason $messages = $validator->getMessages(); foreach ($messages as $message) { echo "$message\n"; } } ``` -------------------------------- ### Basic Validator Chain Usage in PHP Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validator-chains.md Demonstrates creating a validator chain, attaching StringLength and Alnum validators, and validating a username. It shows how to retrieve validation messages. ```php use Laminas\I18n\Validator\Alnum; use Laminas\Validator\StringLength; use Laminas\Validator\ValidatorChain; // Create a validator chain and add validators to it $validatorChain = new ValidatorChain(); $validatorChain->attach(new StringLength(['min' => 6, 'max' => 12])); $validatorChain->attach(new Alnum()); // Validate the username if ($validatorChain->isValid($username)) { // username passed validation } else { // username failed validation; print reasons foreach ($validatorChain->getMessages() as $message) { echo "$message\n"; } } ``` -------------------------------- ### Basic Usage of Laminas File NotExists Validator Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/not-exists.md Demonstrates how to instantiate and use the Laminas\Validator\File\NotExists validator with different methods of providing directory paths. It checks if a given file path does not exist in any of the specified directories. ```php use Laminas\Validator\File\NotExists; // Only allow files that do not exist in ~either~ directories $validator = new NotExists('/tmp,/var/tmp'); // ... or with array notation: $validator = new NotExists(['/tmp', '/var/tmp']); // ... or using options notation: $validator = new NotExists(['directory' => [ '/tmp', '/var/tmp', ]]); // Perform validation if ($validator->isValid('/home/myfile.txt')) { // file is valid } ``` -------------------------------- ### Basic Usage of LaminasValidatorFileNotExists Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/file/not-exists.md Demonstrates how to instantiate and use the NotExists validator to check if a file does not exist in a predefined list of directories. It validates a file path against the configured directories. ```php use Laminas\Validator\File\NotExists; // Only allow files that do not exist in any of the given directories $validator = new NotExists([ 'directory' => ['/tmp', '/var/tmp'], ]); if ($validator->isValid('some-file.txt')) { // File cannot be found in any of the directories provided } else { // A file with the given name was found } ``` -------------------------------- ### Check if Email Exists in Database (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/db.md Example of using LaminasValidatorDbRecordExists to verify if a given email address exists in the 'users' table. ```php // Check that the email address exists in the database $validator = new Laminas\Validator\Db\RecordExists([ 'table' => 'users', 'field' => 'emailaddress', 'adapter' => $dbAdapter, ]); if ($validator->isValid($emailaddress)) { // email address appears to be valid } else { // email address is invalid; print the reasons foreach ($validator->getMessages() as $message) { echo "$message\n"; } } ``` -------------------------------- ### Laminas Validator Constructor with Dependencies and Options Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/writing-validators.md Demonstrates a more advanced constructor for a Laminas validator, accepting a custom service dependency and an options array. This pattern improves testability and compatibility with dependency injection containers like ValidatorPluginManager. ```php namespace MyValid; use Laminas\Validator\AbstractValidator; use Psr\Container\ContainerInterface; final class FlightNumber extends AbstractValidator { public const ERR_INVALID_FLIGHT_NUMBER = 'invalidFlightNumber'; public function __construct(private readonly FlightNumberValidationService $service, array $options = []) { parent::__construct($options); } public function isValid(mixed $value): bool { if (! is_string($value)) { $this->error(self::ERR_INVALID_FLIGHT_NUMBER); return false; } if (! $this->service->isValidFlightNumber($value)) { $this->error(self::ERR_INVALID_FLIGHT_NUMBER); return false; } return true; } } ``` -------------------------------- ### Custom Date Format Validation with LaminasValidatorDate Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/date.md Illustrates how to validate dates with a custom format using the 'format' option. The example shows validation against a year-only format ('Y'). ```php $validator = new Laminas\Validator\Date(['format' => 'Y']); $validator->isValid('2010'); // returns true $validator->isValid('May'); // returns false ``` -------------------------------- ### Set Custom Validation Messages with Laminas StringLength Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/string-length.md This example demonstrates how to customize the validation messages returned by the StringLength validator for specific failure conditions, such as when a string is too long. ```php $validator = new Laminas\Validator\StringLength(['min' => 3, 'max' => 30]); $validator->setMessage('Your string is too long. You typed '%length%' chars.', Laminas\Validator\StringLength::TOO_LONG); ``` -------------------------------- ### Basic Hostname Validation in PHP Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/hostname.md Demonstrates the basic usage of LaminasValidatorHostname to validate a given hostname. It shows how to instantiate the validator, check for validity, and retrieve error messages if the validation fails. ```php isValid($hostname)) { // hostname appears to be valid } else { // hostname is invalid; print the reasons foreach ($validator->getMessages() as $message) { echo "$message\n"; } } ``` -------------------------------- ### Basic Identical Validation in PHP Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/identical.md Demonstrates the basic usage of Laminas\Validator\Identical to check if an input string matches a predefined token. It shows how to instantiate the validator with a token and use the isValid method. ```php $validator = new Laminas\Validator\Identical(['token' => 'donkey'); $validator->isValid('donkey'); // true $validator->isValid('goat'); // false ``` -------------------------------- ### Restricting Max Nesting Depth Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/is-json-string.md Demonstrates how to limit the maximum nesting depth of JSON arrays and objects that the IsJsonString validator will accept. This example sets the maximum depth to 2. ```php $validator = new Laminas\Validator\IsJsonString(['maxDepth' => 2]); $validator->isValid('{"nested": {"object: "here"}}'); // false ``` -------------------------------- ### Setting Allowed JSON Types via Setter Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/is-json-string.md Illustrates using the `setAllow` method to configure which JSON types are permitted by the validator. This example specifically allows only arrays and objects. ```php use Laminas\Validator\IsJsonString; $validator = new IsJsonString(); $validator->setAllow(IsJsonString::ALLOW_ARRAY | IsJsonString::ALLOW_OBJECT); $validator->isValid('1.234'); // false ``` -------------------------------- ### Basic Usage of Callback Validator with a Function Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/callback.md Demonstrates the fundamental use of LaminasValidatorCallback by passing a predefined PHP function as the validation callback. It shows how to instantiate the validator and check the validity of an input. ```php function myMethod(mixed $value): bool { // some validation return true; } $valid = new Laminas\Validator\Callback('myMethod'); if ($valid->isValid($input)) { // input appears to be valid } else { // input is invalid } ``` -------------------------------- ### Basic Usage of Laminas ImageSize Validator Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/image-size.md Demonstrates how to instantiate and use the LaminasValidatorFileImageSize validator with various configurations for minimum and maximum image dimensions. It also shows how to perform the validation against a file path. ```php use Laminas\Validator\File\ImageSize; // Is image size between 320x200 (min) and 640x480 (max)? $validator = new ImageSize(320, 200, 640, 480); // ...or with array notation $validator = new ImageSize([ 'minWidth' => 320, 'minHeight' => 200, 'maxWidth' => 640, 'maxHeight' => 480, ]); // Is image size equal to or larger than 320x200? $validator = new ImageSize([ 'minWidth' => 320, 'minHeight' => 200, ]); // Is image size equal to or smaller than 640x480? $validator = new ImageSize([ 'maxWidth' => 640, 'maxHeight' => 480, ]); // Perform validation with file path if ($validator->isValid('./myfile.jpg')) { // file is valid } ``` -------------------------------- ### Laminas Validator File Md5 Basic Usage Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/md5.md Demonstrates how to instantiate and use the LaminasValidatorFileMd5 validator with single or multiple MD5 hashes, and how to perform validation on a file. ```php use Laminas\Validator\File\Md5; // Does file have the given hash? $validator = new Md5('3b3652f336522365223'); // Or, check file against multiple hashes $validator = new Md5([ '3b3652f336522365223', 'eb3365f3365ddc65365' ]); // Or use options notation: $validator = new Md5(['hash' => [ '3b3652f336522365223', 'eb3365f3365ddc65365' ]]); // Perform validation with file path if ($validator->isValid('./myfile.txt')) { // file is valid } ``` -------------------------------- ### Basic Usage of LaminasValidatorFileSha1 Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/sha1.md Demonstrates how to create and use the Sha1 file validator with single or multiple hash values, and how to perform validation on a file path. ```php use Laminas\Validator\File\Sha1; // Does file have the given hash? $validator = new Sha1('3b3652f336522365223'); // Or check file against multiple hashes: $validator = new Sha1([ '3b3652f336522365223', 'eb3365f3365ddc65365', ]); // Or using options notation: $validator = new Sha1(['hash' => [ '3b3652f336522365223', 'eb3365f3365ddc65365', ]]); // Perform validation with file path if ($validator->isValid('./myfile.txt')) { // file is valid } ``` -------------------------------- ### Configure Validator Chain from Array using ValidatorChainFactory Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validator-chains.md Demonstrates how to define a validator chain configuration as an array and use the ValidatorChainFactory to create an instance of ValidatorChain. This includes setting validator names, options, and priority. ```php use Laminas\Validator\NotEmpty; use Laminas\Validator\StringLength; $chainConfiguration = [ 'First' => [ 'name' => NotEmpty::class, 'break_chain_on_failure' => true, 'options' => [], 'priority' => 1, ], 'Second' => [ 'name' => StringLength::class, 'break_chain_on_failure' => true, 'options' => [ 'min' => 5, 'max' => 10, ], 'priority' => 1, ], ]; use Laminas\Validator\ValidatorChainFactory; $factory = $container->get(ValidatorChainFactory::class); $chain = $factory->fromArray($chainConfiguration); $chain->isValid('Some Value'); ``` -------------------------------- ### Limiting Nesting Depth with IsJsonString in PHP Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/is-json-string.md Illustrates how to limit the maximum nesting level of JSON arrays and objects using the 'maxDepth' option in LaminasValidatorIsJsonString. This example sets a maxDepth of 2. ```php $validator = new Laminas\Validator\IsJsonString(['maxDepth' => 2]); $validator->isValid('{\"nested\": {\"object: \":\"here\"}}'); // false ``` -------------------------------- ### Disable Translation for a Validator Instance (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/intro.md This example demonstrates how to disable the translator for a specific validator instance by setting the 'translatorEnabled' option to false. This is useful when translation is not required for a particular validation. ```php use Laminas\Validator\StringLength; $validator = new StringLength([ 'min' => 8, 'max' => 12, 'translatorEnabled' => false, ]); ``` -------------------------------- ### Basic Usage of Laminas File Count Validator Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v3/validators/file/count.md Demonstrates how to instantiate and use the Laminas File Count validator with minimum and maximum file count options. It validates against the `$_FILES` superglobal. ```php $validator = new Laminas\Validator\File\Count([ 'min' => 1, 'max' => 5, ]); // Setting to the $_FILES superglobal or PSR-7 ServerRequest's `getUploadedFiles()`. $files = $_FILES; if ($validator->isValid($files)) { // Received between 1 and 5 files! } ``` -------------------------------- ### Retrieve Minimum Valid Dimensions - Laminas ImageSize Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/file/image-size.md Shows how to get the minimum valid dimensions set for the Laminas ValidatorFileImageSize validator. The dimensions are returned as an associative array. ```php getImageMin() : array ``` -------------------------------- ### Validate Record Existence with Laminas Select Object (PHP) Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/db.md This code snippet shows how to initialize the `RecordExists` validator with a `Laminas\Db\Sql\Select` object. The `Select` object specifies the table, conditions, and columns to be used for validation. It requires a database adapter to be set before performing validation. ```php use Laminas\Db\Sql\Select; use Laminas\Validator\Db\RecordExists; $select = new Select(); $select ->from('users') ->where ->equalTo('id', $user_id) ->equalTo('email', $email); $validator = new RecordExists($select); // We still need to set our database adapter $validator->setAdapter($dbAdapter); // Validation is then performed as usual if ($validator->isValid($username)) { // username appears to be valid } else { // username is invalid; print the reason $messages = $validator->getMessages(); foreach ($messages as $message) { echo "$message\n"; } } ``` -------------------------------- ### Callback Validation with Constructor Options Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/callback.md Explains how to pass additional options to the callback via the constructor of `LaminasValidatorCallback`. The `callbackOptions` array holds these extra parameters. ```php class MyClass { public static function myMethod($value, $option) { // some validation return true; } } $options = ['some_option_value']; $valid = new Laminas\Validator\Callback([ 'callback' => [MyClass::class, 'myMethod'], 'callbackOptions' => $options, ]); if ($valid->isValid($input)) { // input appears to be valid } else { // input is invalid } ``` -------------------------------- ### Restricting Allowed JSON Types Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/is-json-string.md Shows how to restrict the types of JSON values (booleans, arrays, objects, etc.) accepted by the IsJsonString validator using the 'allow' option. This example excludes boolean values. ```php use Laminas\Validator\IsJsonString; $validator = new IsJsonString([ 'allow' => IsJsonString::ALLOW_ALL ^ IsJsonString::ALLOW_BOOL, ]); $validator->isValid('true'); // false ``` -------------------------------- ### Callback Validation with Class __invoke Method Source: https://github.com/laminas/laminas-validator/blob/3.9.x/docs/book/v2/validators/callback.md Shows how to use a class's magic `__invoke` method as a callback. The validator is initialized with an instance of the class that has the `__invoke` method. ```php class MyClass { public function __invoke($value) { // some validation return true; } } $valid = new Laminas\Validator\Callback(new MyClass()); if ($valid->isValid($input)) { // input appears to be valid } else { // input is invalid } ```