Laminas Validator

repository·3.19.x·Indexed 41 days ago

https://github.com/laminas/laminas-validator

A PHP library providing a suite of common data validators and a mechanism for chaining multiple validators together to perform complex validation logic on single data inputs. It includes built-in validators for numeric comparisons, strings, identity formats (EmailAddress, Hostname, Ip, Uri, Uuid, Iban, Isbn, Barcode), data structures, dates, and database security.

Tokens
69.7K
Snippets
244
Records
329
Agent score
98%

What's inside Laminas Validator

  1. Overview of laminas-validator features

    3.19.x

    The laminas-validator library provides two primary capabilities:

    1. Common Validators: A collection of pre-built validators for checking various data types and formats.
    2. Validator Chaining: A mechanism that allows you to chain multiple validators together. This enables you to apply a sequence of validation rules to a single piece of data in a specific, user-defined order.
  2. Use standard validation classes in laminas-validator

    3.19.x

    The laminas-validator distribution includes a wide range of built-in validator classes for common data types and formats. These include, but are not limited to:

    • Numeric/Comparison: Between, Digits, GreaterThan, LessThan, NumberComparison, Step.
    • Strings/Patterns: Regex, StringLength, Explode, Hex, NotEmpty.
    • Identity/Format: EmailAddress, Hostname, Ip, Uri, Uuid, Iban, Isbn, Barcode.
    • Data Structures: IsArray, IsCountable, IsInstanceOf, InArray.
    • Dates/Time: Date, DateComparison, Timezone.
    • Database/Security: RecordExists, NoRecordExists, CSRF.
    • Files: Specialized file validation classes are available via the file validation sub-module.
  3. Validate files and uploaded files

    3.19.x

    Laminas provides a suite of validator classes specifically designed to verify the properties of files on disk or files uploaded via HTTP. These validators can check for file size, extensions, MIME types, checksums (CRC32, MD5, SHA1), image dimensions, and more.

    Available file-related validators include:

    • Count: Validates the number of files.
    • crc32, md5, sha1, hash: Validates file integrity using specific algorithms.
    • ExcludeExtension, Extension: Validates file extensions.
    • ExcludeMimeType, MimeType: Validates the MIME type of the file.
    • Exists, NotExists: Checks for the existence (or non-existence) of a file.
    • FilesSize, Size: Validates file size constraints.
    • ImageSize, IsImage: Validates image-specific properties.
    • IsCompressed: Checks if a file is compressed.
    • Upload, UploadFile: Validates uploaded file structures.
    • WordCount: Validates the word count within a file.
  4. Use the DateComparison validator

    3.19.x

    The Laminas\Validator\DateComparison validator checks if a given value falls within a specific date range, is after a minimum date, or is before a maximum date.

    By default, comparisons are inclusive (the boundary values themselves are considered valid).

    Important: You must provide at least one of min or max in the options array, otherwise an exception will be thrown.

    $valid = new Laminas\Validator\DateComparison([
        'min' => '2020-01-01',
        'max' => '2020-12-31',
    ]);
    $value = '2020-01-01';
    $result = $valid->isValid($value);
    // returns true
  5. Use additional validators from other Laminas components

    3.19.x

    Beyond the core laminas-validator package, specialized validation logic is available through other Laminas components. Depending on your use case, you may need to install and use validators from:

    • laminas-authentication for identity and credential validation.
    • laminas-captcha for bot/human verification.
    • laminas-i18n for internationalization-related data validation.
    • laminas-session for session-related validation.
  6. Use the Conditional validator to perform conditional validation

    3.19.x

    The Laminas\Validator\Conditional validator allows you to execute a set of validators only if a specific condition is met. This is useful for fields that are only required or must follow certain formats based on the values of other fields in the payload.

    How it works

    1. The validator accepts a rule (a callable) and a list of validators.
    2. The rule is executed, receiving the $context array (the full data payload) as its argument.
    3. If the rule returns false, the validator automatically passes (true), skipping the sub-validators.
    4. If the rule returns true, the validator proceeds to run the specified validators against the value being validated.

    Configuration Options

    • rule: A callable with the signature function(array $context): bool. It must return true to trigger validation or false to skip it.
    • validators: A list of validator specifications used to create a validator chain. The format follows the standard ValidatorChainFactory specifications.
    $validator = new Conditional($chainFactory, [
        'rule' => static function (array $context): bool {
            return (bool) ($context['subscribe'] ?? null) === true;
        },
        'validators' => [
            ['name' => EmailAddress::class],
        ],
    ]);
  7. Validate different types of hostnames

    3.19.x

    You can restrict the validator to specific types of hostnames using the allow option and Laminas\Validator\Hostname constants. You can combine multiple types using bitwise OR (|).

    Available Constants:

    • ALLOW_DNS: Only DNS hostnames (e.g., domain.com).
    • ALLOW_IP: Only IP addresses (e.g., 1.2.3.4).
    • ALLOW_LOCAL: Only local network names (e.g., localhost).
    • ALLOW_URI: RFC3986-compliant addresses (includes WINS, NetInfo, and local hostnames in hosts files).
    • ALLOW_ALL: All of the above types.

    Example: Allow only IP addresses

    use Laminas\Validator\Hostname;
    $validator = new Hostname(['allow' => Hostname::ALLOW_IP]);

    Example: Allow both DNS and Local hostnames

    use Laminas\Validator\Hostname;
    $validator = new Hostname([
        'allow' => Hostname::ALLOW_DNS | Hostname::ALLOW_LOCAL,
    ]);
    use Laminas\Validator\Hostname;
    
    // To check for IP addresses only
    $validator = new Hostname(['allow' => Hostname::ALLOW_IP]);
    
    // To accept DNS and Local hostnames
    $validator = new Hostname([
        'allow' => Hostname::ALLOW_DNS | Hostname::ALLOW_LOCAL,
    ]);
  8. Use the Explode Validator to validate array items

    3.19.x

    The Laminas\Validator\Explode validator iterates over an array and executes a specific validator on every individual item. It is useful when you have a collection of values and want to ensure every single one meets a certain criteria (e.g., checking if all IDs in an array exist in a database).

    $inArrayValidator = new Laminas\Validator\InArray([
        'haystack' => [1, 2, 3, 4, 5, 6],
    ]);
    
    $explodeValidator = new Laminas\Validator\Explode([
        'validator' => $inArrayValidator
    ]);
    
    $explodeValidator->isValid([1, 4, 6]);    // returns true
    $explodeValidator->isValid([1, 4, 6, 8]); // returns false
  9. Validate file contents using Crc32

    3.19.x

    The Laminas\Validator\File\Crc32 validator checks if a file's hashed contents match one or more provided CRC32 hashes. It is a specialized subclass of the Hash validator that only supports the crc32 algorithm.

    Requirement: This validator requires the PHP hash extension with crc32 support enabled.

    // Does file have the given hash?
    $validator = new \Laminas\Validator\File\Crc32('3b3652f');
    
    // Or, check file against multiple hashes
    $validator = new \Laminas\Validator\File\Crc32(['3b3652f', 'e612b69']);
    
    // Perform validation with file path
    if ($validator->isValid('./myfile.txt')) {
        // file is valid
    }
  10. Implement dependent vs independent validation conditions

    3.19.x

    When writing isValid(), you can choose between two logic patterns depending on how you want to report errors:

    Dependent Conditions (Sequential)

    Use this pattern if you want to stop validation as soon as the first error is encountered. This is useful when subsequent checks depend on the previous ones passing (e.g., checking if a value is numeric before checking if it is within a range).

    Pattern:

    if (! condition1) {
        $this->error(ERR_1);
        return false;
    }
    if (! condition2) {
        $this->error(ERR_2);
        return false;
    }
    return true;

    Independent Conditions (Cumulative)

    Use this pattern if you want to report all reasons why a value failed validation. This is useful for complex requirements like password strength, where a user should see all missing criteria at once.

    Pattern:

    $isValid = true;
    if (! condition1) {
        $this->error(ERR_1);
        $isValid = false;
    }
    if (! condition2) {
        $this->error(ERR_2);
        $isValid = false;
    }
    return $isValid;
  11. Refactor to composition instead of inheritance for validators

    3.19.x
    In version 3, many validator classes have been marked as final. To reduce maintenance burden and encourage best practices, you should favor composition over inheritance. Even if a validator is not explicitly marked as final, it is recommended not to extend from it, as future major releases may prohibit inheritance entirely.
  12. Handle array tokens containing a 'token' key

    3.19.x

    When configuring the Identical validator via an options array, if the actual value you want to use as the token is an array that contains its own key named token, you must wrap it in an additional token key to prevent the validator from misinterpreting the configuration.

    • To validate against the integer 123: ['token' => 123]
    • To validate against the array ['token' => 123]: ['token' => ['token' => 123]]
    // Validates against the array ['token' => 123]
    $valid = new Laminas\Validator\Identical(['token' => ['token' => 123]]);