Skip to content

MarwanAlsoltany/mighty

Repository files navigation

Mighty

The last validation library you will ever need!

PHP Version Latest Version on Packagist Total Downloads License Maintenance Documentation
GitHub Continuous Integration GitHub Continuous Deployment Codecov

Open in Visual Studio Code

Tweet Star

Table of Contents

Installation
About Mighty
Quickstart
mVEL
Examples
Constraints
Validations
Documentation
Specification
Changelog


If you like this project and would like to support its development, giving it a ⭐ would be appreciated!



Key Features

  1. Zero dependencies.
  2. Framework agnostic, can be integrated in any codebase.
  3. Expressive, intuitive and easy to get along with over 250 built-in validation rules.

Mighty Demo


Installation

composer require marwanalsoltany/mighty

About Mighty

Validation is a common task in any web application. Data passed to the application via forms —or any type of input for that matter— must always be validated against a set of rules. Mighty can handle in an easy and expressive way.

Mighty is fast, powerful, robust, and easy to use validation library that is just fun to work with, it makes validating any data a breeze. Thanks to the power of the Mighty Validation Expression Language (mVEL) it is not like anything you've seen before. With its validation approach and over 250 built-in rules there is pretty much nothing that you cannot validate with it, in a very expressive and compact manner. Simply put, Mighty is validation on steroids! It is indeed the last validation library you will ever need.

Mighty provides several different approaches to validate data. It's most common use-case is validating incoming data via HTTP requests, but it of course is not limited to that; Mighty provides also attributes in the form of constraints to easily validate models and/or any kind of objects.

Mighty includes a wide variety of convenient validation rules that you may apply as a single rule or combine them with each other using operators to build up even more complex validations.

Quickstart

To learn about Mighty's powerful validation features, let's cut straight to the point and take a look at some examples:

General Data Validation

Validating form data using the Validator::class:

use MAKS\Mighty\Validator;

$validator = new Validator();

$validator
    ->setData([
        'name'     => 'John Doe',
        'username' => 'john.doe',
        'password' => 'Super@Secret#123',
        'email'    => '[email protected]',
        'hobbies'  => ['coding', 'design', 'sports'],
    ])
    ->setValidations([
        // required&string&between:3,255
        'name'      => $validator->validation()->required()->string()->between(3, 255),
        // required&string&matches:/[a-z0-9._-]/i
        'username'  => $validator->validation()->required()->string()->matches('/[a-z0-9._-]/i'),
        // required&string&min:8
        'password'  => $validator->validation()->required()->string()->min(8),
        // required&email
        'email'     => $validator->validation()->required()->email(),
        // null^(required&array&max:5)
        'hobbies'   => $validator
            ->validation()
            ->null()
            ->xor()
            ->group(fn ($validation) => $validation
                ->array()
                ->max(5)
            ),
        // null|(if:${hobbies.validations.array}&(string&min:3))
        // hobby can be null or a string with at least 3 characters if hobbies is an array
        'hobbies.*' => $validator
            ->validation()
            ->null()
            ->or()
            ->group(fn ($validation) => $validation
                ->if('${hobbies.validations.array}')
                ->open()
                ->string()
                ->min(3)
                ->close()
            ),
    ])
    ->validate();

$result = $validator->isOK(); // boolean result of the overall validation result

$errors = $validator->getErrors(); // an array of results of validations that failed

$results = $validator->getResults(); // an array of results of all validations

$validator->check(); // void or throws an exception with a nicely formatted message of what exactly went wrong

Objects Validation

Validating the state of an object using Constraint::class attributes:

use MAKS\Mighty\Validation\Strategy;
use MAKS\Mighty\Validation\Behavior;
use MAKS\Mighty\Validation\Operator;
use MAKS\Mighty\Validation\Constraint;
use MAKS\Mighty\Validation\Constraint as Assert;
use MAKS\Mighty\Validation\Constraint\ValidatableObjectInterface;
use MAKS\Mighty\Validation\Constraint\ValidatableObjectTrait;


class ValidatableObject implements ValidatableObjectInterface
{
    use ValidatableObjectTrait;


    #[Assert\Rule\Equals('CONST')]
    public const CONST = 'CONST';

    #[Assert\Rule\In(['STATIC', 'VAR'])]
    public static $static = 'VAR';

    #[Assert\Rule\StringConstraint]
    #[Assert\Rule\StringCharset('UTF-8')]
    #[Assert\Rule\Between(3, 99)]
    public $default = 'DEFAULT';

    #[Assert\Rule\StringConstraint]
    #[Assert\Rule\StringContains('<element>')]
    #[Assert\Rule\Xml]
    public $xml = '<?xml version="1.0"?><element></element>';

    #[Assert\Rule\ArrayConstraint]
    #[Assert\Shape([
        'string' => new Assert\Rule\Str,
        'array'  => new Assert\Rule\Arr,
    ])]
    public $array = [
        'string' => 'value',
        'array'  => [],
    ];

    #[Assert\Rule\ObjectConstraint]
    #[Assert\Rule\ObjectIsInstanceOf(ValidatableObjectInterface::class)]
    #[Assert\Valid(message: 'Not valid')]
    public $object;

    #[Assert\Callback('is_scalar', 'Data is not scalar')]
    #[Constraint('string&min:3', strategy: Strategy::FailLazy, messages: [
        'string' => 'Must be string.',
        'min'    => 'Must be longer than ${@arguments.0}.',
    ])]
    public function getDefault()
    {
        return $this->default;
    }

    #[Assert\Compound([
        new Assert\Rule\Str,
        new Assert\Compound([
            new Assert\Rule\Arr,
            new Assert\Compound([
                new Assert\Rule\Blank,
            ], Operator::Not),
        ], Operator::And),
    ], Operator::Xor, Behavior::Pessimistic, Strategy::FailLazy)]
    public static function getStaticProperty()
    {
        return static::$static;
    }
}

$object = new ValidatableObject();

$result = $object->isValid(); // boolean result of the overall validation result

$results = $object->validate(); // an array of results of all validations

$object->check(); // void or throws an exception with a nicely formatted message of what exactly went wrong

An example of the output of validating a validatable object would look like this:

// check out the previous snippet see the used constraints

$object = new ValidatableObject();
$object->object = new class implements ValidatableObjectInterface {
    use ValidatableObjectTrait;
    // some properties and their validation constraints ...
};
$object->default = null; // this must be a string

$object->check();

// ValidationFailedException::class
// Data failed to pass the validation.
// (01) The value (null) of the "ValidatableObject->default" property failed to pass the validation [string]. Problem: Value must be a string.
// (02) The value (null) of the "ValidatableObject->default" property failed to pass the validation [string.charset:"UTF-8"]. Problem: Value must be encoded in one of the following charsets: ["UTF-8"].
// (03) The value (null) of the "ValidatableObject->default" property failed to pass the validation [between:3,99]. Problem: Value must be between 3 and 99 or have a value/count/length that is between 3 and 99.
// (04) The return value (null) of the "ValidatableObject->getDefault()" method failed to pass the validation [callback]. Problem: Data is not scalar.
// (05) The return value (null) of the "ValidatableObject->getDefault()" method failed to pass the validation [string&min:3]. Problems: Must be string; Must be longer than 3.

Check also ValidatableObject and ValidatableObjectChild.

■ Hint: More examples can be found in the Examples section.


Mighty Validation Expression Language

Mighty has the concept of Validation Expression. The Validation Expression in its simplest forms is just a string that describes how Mighty should validate the given data. These strings are based on the Mighty Validation Expression Language Specification (mVEL). mVEL is pretty simple, human-readable and easy to cope with. It is a combination of well established concepts and/or specifications like Boolean Algebra, Bitwise Operators, JSON, and CSV.

Therefore, Validation Expression may be defined as a string that contains some rules separated by Bitwise Operators which will build an expression that when evaluated using Boolean Algebra logic, will result in the final result of the validation. The rules can have arguments, the types of these arguments can be denoted using the same rules of JSON types. A rule can also have multiple arguments and the arguments are separated by commas (CSV).

For example  required&string&between:2,255|null  is a valid Validation Expression, this expression can be understood as the following:

  1. The expression has four rules.
  2. The expression contains the rules:
    1. required Asserts that the input is present.
    2. string Asserts that the input is a string.
    3. between:2,255 Asserts that the input is a string with a length between 2 and 255.
    4. null Asserts that the input is null.
  3. The final result is the result of evaluating the expression resulting from the result of each rule glued together using bitwise operators.

The required&string&between:2,255|null expression means that the input must be present; AND of type string; AND between 2 and 255 in length; OR null. So it's a nullable string that when is not null must be between 2 and 255 characters long.

Lets say the the input was "Mighty is Awesome!", the result of the expression required&string&between:2,255|null against that input would be 1&1&1|0 which will result in 1 which is true, if the input was null the result would be 0&0&0|1 = 1, if the input was X the result would be 0&0&0|0 = 0, etc ...

Unlike other validations implementations, the concept of Boolean Algebra using Bitwise Operators, gives the possibility to build up complex validations that are very readable and compact while keeping the rules to a minimum number, reusing existing logic in reversed or compound manner, and finally keeping the code base as DRY as it can be. The benefits can be summarized in the following points:

  1. A rule can be NOTed (using ~) to do the exact opposite of what it normally does.
  2. A complex rule can be the result of ANDing (using &), ORing (using |), or XORing (using ^), two or more simple rules.
  3. Rules can be grouped together and/or given higher precedence by using parentheses, namely OPEN (using () and CLOSE (using )).
  4. A Validation Expression can also have behavior, which is a character the prefixes the Validation Expression string that will affect all rules. Available behaviors are:
    1. NORMAL: execute all rules, default behavior (no prefix).
    2. OPTIMISTIC: stop executing rules after the first success (? prefix).
    3. PESSIMISTIC: stop executing rules after the first failure (! prefix).
  5. Readability can be improved by aliasing some rules or adding rules sets as macros and executing them using the [macro] syntax.

Also the concept of JSON ensures arguments data-types safety, and the concept of CSV makes sure the arguments list has clear parsing rules.

The nicest thing, you don't have to memorize all the rules nor the Validation Expression Language syntax. The Validation class is a fluent interface that can be used to build a Validation Expression. It knows about all Mighty available rules and has full IDE-Intellisense support to make it as easy as it gets. For example:

use MAKS\Mighty\Validation;

// the validation expression: `required&string&between:2,255|null`
// can be constructed using the Validation::class as follows:
$validation = (new Validation())->required()->string()->between(2, 255)->or()->null(); // AND is the default operator
// or statically:
$validation = Validation::required()->string()->between(2, 255)->or()->null();

■ Fact: It usually takes more words to describe what a validation expression does than the validation expression itself!


Examples

Here are some examples of real world scenarios:

Validating a Single Value

use MAKS\Mighty\Validator;

$result = ($validator = new Validator())
    ->validateOne(
        '123',
        $validator
            ->validation()
            // can be an integer or float or a string that is numeric
            // this example is only for demonstration only,
            // the same result can be achieved using numeric() only
            ->integer()->or()->float()->or()->group(
                fn ($validation) => $validation->string()->and()->numeric()
            )
    )
    ->toArray();

// $result would look something like this:
[
    'value' => '123',
    'result' => true,
    'validations' => [
        'integer' => false,
        'float' => false,
        'string' => true,
        'numeric' => true,
    ],
    'errors' => [],
    'metadata' => [
        'basis' => 'integer|float|(string&numeric)',
        'rules' => 'integer|float|(string&numeric)',
        'expression' => '0|0|(1&1)',
    ],
];

// you can also simply use the static helper Validator::validateData($data, $validation);

Validating Structured Data

use MAKS\Mighty\Validator;
use App\Service\HaveIBeenPwnedService as PasswordService;

$validator = new Validator();

$data = [
    'name'       => 'John Doe',
    'age'        => 32,
    'email'      => '[email protected]',
    'username'   => 'john.doe',
    'password'   => 'Secret@123',
    'image'      => '/path/to/image.png',
    'submission' => 'now',
    'consent'    => 'yes',
    'data'       => [
        'nickname' => 'JOE',
        'number'   => 7,
        'hobbies'  => [
            'coding',
            'cooking',
            'reading',
        ]
    ],
];

$validations = [
    'name'           => $validator->validation()->required()->string()->stringCharset(['UTF-8', 'ASCII'])->pessimistic(),
    // or using mVEL => required&string&string.charset:'["UTF-8","ASCII"]'
    'age'            => $validator->validation()->required()->integer()->min(18),
    // or using mVEL => required&integer&min:18
    'email'          => $validator->validation()->required()->email()->macro('gmail'),
    // or using mVEL => required&email&[gmail]
    'username'       => $validator->validation()->required()->username(),
    // or using mVEL => required&username
    'password'       => $validator->validation()->required()->password()->callback(fn ($input) => !PasswordService::isPwned($input)),
    // or using mVEL => required&password (NOTE: callback ist not possible, it requires a Validation::class instance that is bound to the Validator::class instance)
    'image'          => $validator->validation()->null()->xor()->group(fn () => $this->image()->imageDimensions(1920, 1080, '<=')),
    // or using mVEL => null^(image&image.dimensions:1920,1080,"<=")
    'submission'     => $validator->validation()->required()->datetime()->datetimeLt('2022-12-07'),
    // or using mVEL => required&datetime&datetime.lt:"2022-12-07"
    'consent'        => $validator->validation()->assert('${age.value}', 18, '>=')->or()->accepted()->or()->assertEquals('${this}', 'granted')->optimistic(),
    // or using mVEL => ?assert:${age.value},18,">="|accepted|assert.equals:${this},"granted"
    'data'           => $validator->validation()->required()->array()->arrayHasKey('nickname'),
    // or using mVEL => required&array&array.hasKey:"nickname"
    'data.*'         => $validator->validation()->scalar()->or()->array()->optimistic(),
    // or using mVEL => ?scalar|array
    'data.nickname'  => $validator->validation()->string()->min(2)->max(32),
    // or using mVEL => string&min:2&max:32
    'data.hobbies.*' => $validator->validation()->ifEq('${data.hobbies.validations.array}', false)->or()->group(fn () => $this->string()->min(3)),
    // or using mVEL => if.eq:${data.hobbies.validations.array},false|(string&min:3)
];

$labels = [
    'name'     => 'Name',
    'age'      => 'Age',
    'email'    => 'E-Mail',
    'password' => 'Password',
    'image'    => 'Image',
    'data'     => 'Data',
    'data.*'   => 'Value of data',
    'consent'  => 'Consent',
];

$messages = [
    '*' => [ // this will be expanded for all fields
        'required' => '${@label} is a required field.',
    ],
    'age' => [
        'min' => '${@label} must be at least ${@arguments.0}.',
    ],
    'username' => [
        'matches' => '${@label} must contain letters, numbers, and the following characters ".-_" only.',
    ],
    'consent' => [
        'assert' => 'You must be at least ${@arguments.1} years old to submit this form.',
    ]
];

$validator
    ->setData($data)
    ->setValidations($validations)
    ->setMessages($messages)
    ->setLabels($labels)
    ->validate();

$results = $validator->getResults();

// $result should look something like this:
[
    // this will actually be a Result object
    // array syntax is used here for demonstration purposes
    'name' => [
        'key' => 'name',
        'value' => 'John Doe',
        'result' => true,
        'validations' => [
            'required' => true,
            'string' => true,
            'string.charset' => true,
        ],
        'errors' => [],
        'metadata' => [
            'basis' => '!required&string&string.charset:["UTF-8","ASCII"]',
            'rules' => 'required&string&string.charset:["UTF-8","ASCII"]',
            'expression' => '1&1&1',
        ],
    ],
    // other validations ...
];

// you can also simply use the static helper Validator::validateData($data, $validations);

■ Hint: When providing message overrides to the Validator::class, it is advised to use the Rule\Validation::class to set array keys. This class contains all Mighty built-in rules names as class constants.

Extending the Validator

The validator can be extended in three ways:

  • By adding a rule.
  • By adding an alias.
  • By adding a macro.
use MAKS\Mighty\Validator;
use MAKS\Mighty\Rule;

$validator = new Validator();

// adding a new rule
$validator->addRule(
    (new Rule())
        ->name('equals')
        ->arguments(['string'])
        ->callback(fn (string $input, mixed $expected): bool => $input == $expected)
        ->parameters(['@input', '@arguments.0'])
        ->comparison(['@output', '===', true])
        ->example('equals:value')
        ->description('Asserts that the input is equal to the given value.')
);

// adding a new rule alias
$validator->addRuleAlias('eq', 'equals');

// adding a new rules macro
$validator->addRuleMacro('gmail', 'string&email&matches:"/@gmail\.com$/i"');

$results = $validator->validateAll(
    [
        'name'  => 'John',
        'email' => '[email protected]',
    ],
    [
        'name'  => 'eq:John',
        'email' => 'required&[gmail]',
    ]
);

// $results should look like this:
[
    // items will actually be a Result object
    // array syntax is used here for demonstration purposes
    'name' => [
        'key' => 'name',
        'value' => 'John',
        'result' => true,
        'validations' => [
            'eq' => true,
        ],
        'errors' => [],
        'metadata' => [
            'basis' => 'eq:John',
            'rules' => 'eq:John',
            'expression' => '1',
        ],
    ],
    'email' => [
        'key' => 'email',
        'value' => '[email protected]',
        'result' => false,
        'validations' => [
            'required' => true,
            'string' => true,
            'email' => true,
            'matches' => false,
        ],,
        'errors' => [],
        'metadata' => [
            'basis' => 'required&[gmail]',
            'rules' => 'required&(string&email&matches:"/@gmail\.com$/i")',
            'expression' => '1&(1&1&0)',
        ],
    ],
];

■ Hint: Check out the default rules, aliases, and macros of the Validator to see more examples.


Constraints

Mighty consists of over 250 rules/attributes that can be used to validate any data or the values of classes, class constants, properties, and methods.

The attributes are split into three main groups:

  1. Generic Constraint Attributes
  2. Special Constraint Attributes
  3. Rule Constraint Attributes

Generic Constraint Attributes Group

The Generic Constraint Attributes are located under the MAKS\Mighty\Validation namespace.

This group consists currently of one attribute only; that is the Constraint attribute. This attribute takes a Validation Expression to validate the data it is applied to. It is also the base class for all other attributes.

Special Constraint Attributes Group

The Special Constraint Attributes are located under the MAKS\Mighty\Validation\Constraint namespace.

This group contains attributes that do a specific job that is available only in the context of attributes. It consists of the following attributes:

  • Rule: This attribute is used to validate any data using a single validation rule. It is also the base class for all attributes in the Rule Constraint Attributes Group.
  • Callback: This attribute is used to validate any data using a callback function.
  • Valid: This attribute is used to validate the validity of a validatable object.
  • Shape: This attribute is used to validate the shape of an array or object. Note that this is the only attribute that validates a set of values (structured data) rather than a single value.
  • Compound: This attribute is used to combine a set of constraints to build up a Validation Expression. The constraints can be combined using any operator, and can also have a behavior. It serves as an object-oriented way to build up a Validation Expression.

■ Note: Note that the constraints that are allowed to be used with the Shape::class and Compound::class attributes must be an actual instances of the Constraint::class, Rule::class, or Compound::class. The Callback::class, Valid::class, or Shape::class of the Special Constraint Attributes Group are NOT allowed. If you have a need for this feature, open an issue and we'll discuss implementing it

Rule Constraint Attributes Group

The Rule Constraint Attributes are located under the MAKS\Mighty\Validation\Constraint\Rule namespace.

This group contains attributes that are based on a single validation rule. It consists of most of the attributes Mighty provides. Refer to the Validations section for the full list.

Adding a Custom Constraint

Mighty has a huge list of built-in constraints, it's really rare that you will need anything other than what Mighty provides. Nonetheless, sometimes the need arises for a custom constraint, the is how you can achieve that:

<?php

declare(strict_types=1);

namespace App\Validation\Constraint;

use Attribute;
use MAKS\Mighty\Rule;
use MAKS\Mighty\Result;
use MAKS\Mighty\Validation\Strategy;
use MAKS\Mighty\Validation\Constraint;
use MAKS\Mighty\Validation\Constraint\ValidatesOne;
// use the ValidatesMany interface if your Constraint returns a collection of Result objects
use MAKS\Mighty\Validation\Constraint\ValidatesMany;

#[Attribute(
    Attribute::TARGET_PROPERTY |
    Attribute::TARGET_METHOD
)]
class MyCustomConstraint extends Constraint implements ValidatesOne
{
    public function __construct(
        ?string $message = null,
        Strategy $strategy = Strategy::FailFast,
    ) {
        parent::__construct(
            validation: 'app.myCustomConstraint',
            messages: ['app.myCustomConstraint' => $message],
            strategy: $strategy
        );
    }


    public function validate(mixed $value = null): Result
    {
        // it is really up to you, how you handle this
        // you will just work with a normal Mighty Validator
        // here we're just preparing the data to pass to the Validator
        $name        = '';
        $data        = [$name => $value];
        $validations = [$name => $this->validation];
        $messages    = [$name => [$this->validation => $this->messages[$this->validation] ?? null]];
        $labels      = [$name => static::class];

        // you can reuse the built-in rules or
        // add you own Rule that handles your custom logic
        $result = $this
            ->getValidator()
            ->addRule(
                // see MAKS\Mighty\Rule for more info
                (new Rule())
                    ->setName('app.myCustomConstraint')
                    ->setCallback(static fn ($input) => $input /* here comes your logic */)
                    ->setParameters(['@input']) // rule callback dependencies
                    ->setMessage('${@label} must follow my custom constraint validation.') // this is the default message
            )
            ->setData($data)
            ->setValidations($validations)
            ->setMessages($messages)
            ->setLabels($labels)
            ->validate();

        return $result[$name]; // if you implement ValidatesMany, you will just return $result
    }
}

■ Note: Custom constraints are considered a part of the Special Constraint Attributes Group (i.e. not allowed to be used with/inside the Shape::class and Compound::class constraints)


Validations

The following table lists all available rules including their Attribute and Method equivalents:

Rules and Aliases

No. Rule Description Attribute / Method
001 Name: null
Usage: null
Asserts that the input is null. Attribute:
NullConstraint::class
Method:
Validation::null()
002 Name: boolean
Usage: boolean
Asserts that the input is a boolean. Attribute:
Boolean::class
Method:
Validation::boolean()
003 Name: integer
Usage: integer
Asserts that the input is an integer. Attribute:
Integer::class
Method:
Validation::integer()
004 Name: float
Usage: float
Asserts that the input is a float. Attribute:
FloatConstraint::class
Method:
Validation::float()
005 Name: numeric
Usage: numeric
Asserts that the input is numeric. Attribute:
NumericConstraint::class
Method:
Validation::numeric()
006 Name: string
Usage: string
Asserts that the input is a string. Attribute:
StringConstraint::class
Method:
Validation::string()
007 Name: scalar
Usage: scalar
Asserts that the input is a scalar. Attribute:
Scalar::class
Method:
Validation::scalar()
008 Name: array
Usage: array
Asserts that the input is an array. Attribute:
ArrayConstraint::class
Method:
Validation::array()
009 Name: object
Usage: object
Asserts that the input is an object. Attribute:
ObjectConstraint::class
Method:
Validation::object()
010 Name: callable
Usage: callable
Asserts that the input is a callable. Attribute:
CallableConstraint::class
Method:
Validation::callable()
011 Name: iterable
Usage: iterable
Asserts that the input is an iterable. Attribute:
IterableConstraint::class
Method:
Validation::iterable()
012 Name: countable
Usage: countable
Asserts that the input is a countable. Attribute:
Countable::class
Method:
Validation::countable()
013 Name: resource
Usage: resource
Asserts that the input is a resource. Attribute:
ResourceConstraint::class
Method:
Validation::resource()
014 Name: type
Usage: type:'["int","float"]'
Asserts that the input is one of the given types. Attribute:
Type::class
Method:
Validation::type(string|array $type)
015 Name: type.debug
Usage: type.debug:string
Asserts that the input is of the given type using get_debug_type(). Attribute:
TypeDebug::class
Method:
Validation::typeDebug(string $type)
016 Name: alpha
Usage: alpha
Asserts that the input consists of alphabetic characters only. Attribute:
Alpha::class
Method:
Validation::alpha()
017 Name: alnum
Usage: alnum
Asserts that the input consists of alphanumeric characters only. Attribute:
Alnum::class
Method:
Validation::alnum()
018 Name: lower
Usage: lower
Asserts that the input consists of lowercase characters only. Attribute:
Lower::class
Method:
Validation::lower()
019 Name: upper
Usage: upper
Asserts that the input consists of uppercase characters only. Attribute:
Upper::class
Method:
Validation::upper()
020 Name: cntrl
Usage: cntrl
Asserts that the input consists of control characters only. Attribute:
Cntrl::class
Method:
Validation::cntrl()
021 Name: space
Usage: space
Asserts that the input consists of whitespace characters only. Attribute:
Space::class
Method:
Validation::space()
022 Name: punct
Usage: punct
Asserts that the input consists of punctuation characters only. Attribute:
Punct::class
Method:
Validation::punct()
023 Name: graph
Usage: graph
Asserts that the input consists of graphic characters only (characters that create a visible output). Attribute:
Graph::class
Method:
Validation::graph()
024 Name: print
Usage: print
Asserts that the input consists of printable characters only. Attribute:
PrintConstraint::class
Method:
Validation::print()
025 Name: digit
Usage: digit
Asserts that the input consists of a digits only (numeric characters). Attribute:
Digit::class
Method:
Validation::digit()
026 Name: xdigit
Usage: xdigit
Asserts that the input represent hexadecimal digits. Attribute:
Xdigit::class
Method:
Validation::xdigit()
027 Name: booleanLike
Usage: booleanLike
Asserts that the input is a value that can be parsed as a boolean (TRUE: true, "true", "1", "on", "yes"; FALSE: false, "false", "0", "off", "no", "", null). Attribute:
BooleanLike::class
Method:
Validation::booleanLike()
028 Name: integerLike
Usage: integerLike:0,100
Asserts that the input is a value that can be parsed as an integer within the specifed range. Attribute:
IntegerLike::class
Method:
Validation::integerLike(int $min = PHP_INT_MIN, int $max = PHP_INT_MAX)
029 Name: integerLike.allowOctal
Usage: integerLike.allowOctal:0,100
Asserts that the input is a value that can be parsed as an integer within the specifed range and can be in octal notation. Attribute:
IntegerLikeAllowOctal::class
Method:
Validation::integerLikeAllowOctal(int $min = PHP_INT_MIN, int $max = PHP_INT_MAX)
030 Name: integerLike.allowHex
Usage: integerLike.allowHex:0,100
Asserts that the input is a value that can be parsed as an integer within the specifed range and can be in hexadecimal notation. Attribute:
IntegerLikeAllowHex::class
Method:
Validation::integerLikeAllowHex(int $min = PHP_INT_MIN, int $max = PHP_INT_MAX)
031 Name: floatLike
Usage: floatLike:1.0,100.0
Asserts that the input is a value that can be parsed as a float within the specifed range. Attribute:
FloatLike::class
Method:
Validation::floatLike(float $min = PHP_FLOAT_MIN, float $max = PHP_FLOAT_MAX)
032 Name: floatLike.allowThousands
Usage: floatLike.allowThousands:1.0,100.0
Asserts that the input is a value that can be parsed as a float within the specifed range. Attribute:
FloatLikeAllowThousands::class
Method:
Validation::floatLikeAllowThousands(float $min = PHP_FLOAT_MIN, float $max = PHP_FLOAT_MAX)
033 Name: regexp
Usage: regexp:"/[a-z]/i"
Asserts that the input matches a Perl-compatible regular expression. Attribute:
Regexp::class
Method:
Validation::regexp(string $pattern)
034 Name: ip
Usage: ip
Asserts that the input is an IP address. Attribute:
Ip::class
Method:
Validation::ip()
035 Name: ip.v4
Usage: ip.v4
Asserts that the input is an IPv4 address. Attribute:
IpV4::class
Method:
Validation::ipV4()
036 Name: ip.v6
Usage: ip.v6
Asserts that the input is an IPv6 address. Attribute:
IpV6::class
Method:
Validation::ipV6()
037 Name: ip.notReserved
Usage: ip.notReserved
Asserts that the input is an IP address not within reserved IPs range. Attribute:
IpNotReserved::class
Method:
Validation::ipNotReserved()
038 Name: ip.notPrivate
Usage: ip.notPrivate
Asserts that the input is an IP address not within private IPs range. Attribute:
IpNotPrivate::class
Method:
Validation::ipNotPrivate()
039 Name: mac
Usage: mac
Asserts that the input is a MAC address. Attribute:
Mac::class
Method:
Validation::mac()
040 Name: url
Usage: url
Asserts that the input is a URL. Attribute:
Url::class
Method:
Validation::url()
041 Name: url.withPath
Usage: url.withPath
Asserts that the input is a URL that contains a path. Attribute:
UrlWithPath::class
Method:
Validation::urlWithPath()
042 Name: url.withQuery
Usage: url.withQuery
Asserts that the input is a URL that contains a query. Attribute:
UrlWithQuery::class
Method:
Validation::urlWithQuery()
043 Name: email
Usage: email
Asserts that the input is an email address. Attribute:
Email::class
Method:
Validation::email()
044 Name: email.withUnicode
Usage: email.withUnicode
Asserts that the input is an email address (unicode allowed). Attribute:
EmailWithUnicode::class
Method:
Validation::emailWithUnicode()
045 Name: domain
Usage: domain
Asserts that the input is a domain. Attribute:
Domain::class
Method:
Validation::domain()
046 Name: domain.isActive
Usage: domain.isActive
Asserts that the input is an active domain. Works with domains and emails. Attribute:
DomainIsActive::class
Method:
Validation::domainIsActive()
047 Name: file
Usage: file
Asserts that the input is a file (can be a file, a link, or a directory). Attribute:
File::class
Method:
Validation::file()
048 Name: file.isFile
Usage: file.isFile
Asserts that the input is a file. Attribute:
FileIsFile::class
Method:
Validation::fileIsFile()
049 Name: file.isLink
Usage: file.isLink
Asserts that the input is a link. Attribute:
FileIsLink::class
Method:
Validation::fileIsLink()
050 Name: file.isDirectory
Usage: file.isDirectory
Asserts that the input is a directory. Attribute:
FileIsDirectory::class
Method:
Validation::fileIsDirectory()
051 Name: file.isExecutable
Usage: file.isExecutable
Asserts that the input is a file and is executable. Attribute:
FileIsExecutable::class
Method:
Validation::fileIsExecutable()
052 Name: file.isWritable
Usage: file.isWritable
Asserts that the input is a file and is writable. Attribute:
FileIsWritable::class
Method:
Validation::fileIsWritable()
053 Name: file.isReadable
Usage: file.isReadable
Asserts that the input is a file and is readable. Attribute:
FileIsReadable::class
Method:
Validation::fileIsReadable()
054 Name: file.isUploaded
Usage: file.isUploaded
Asserts that the input is a file that is uploaded via HTTP POST. Attribute:
FileIsUploaded::class
Method:
Validation::fileIsUploaded()
055 Name: file.size
Usage: file.size:1024
Asserts that the input is a file and the size is equal to the given size in bytes. Attribute:
FileSize::class
Method:
Validation::fileSize(int $sizeInBytes)
056 Name: file.size.lte
Usage: file.size.lte:1024
Asserts that the input is a file and the size is less than or equal to the given size in bytes. Attribute:
FileSizeLte::class
Method:
Validation::fileSizeLte(int $sizeInBytes)
057 Name: file.size.gte
Usage: file.size.gte:1024
Asserts that the input is a file and the size is greater than or equal to the given size in bytes. Attribute:
FileSizeGte::class
Method:
Validation::fileSizeGte(int $sizeInBytes)
058 Name: file.dirname
Usage: file.dirname:/path/to/dir
Asserts that the input is a file and its dirname is equal to the given dirname. Attribute:
FileDirname::class
Method:
Validation::fileDirname(string $dirname)
059 Name: file.basename
Usage: file.basename:file.ext
Asserts that the input is a file and its basename is equal to the given basename. Attribute:
FileBasename::class
Method:
Validation::fileBasename(string $basename)
060 Name: file.filename
Usage: file.filename:file
Asserts that the input is a file and its filename is equal to the given filename. Attribute:
FileFilename::class
Method:
Validation::fileFilename(string $filename)
061 Name: file.extension
Usage: file.extension:ext
Asserts that the input is a file and its extension is equal to the given extension. Attribute:
FileExtension::class
Method:
Validation::fileExtension(string $extension)
062 Name: file.mime
Usage: file.mime:text/plain
Asserts that the input is a file and its MIME type is one of the given MIME types. Attribute:
FileMime::class
Method:
Validation::fileMime(string|array $mine)
063 Name: image
Usage: image
Asserts that the input is an image file (jpg, jpeg, png, gif, bmp, svg, or webp). Attribute:
Image::class
Method:
Validation::image()
064 Name: image.width
Usage: image.width:1920
Asserts that the input is an image and its width is equal to the given width in pixels. Attribute:
ImageWidth::class
Method:
Validation::imageWidth(int $width)
065 Name: image.width.lte
Usage: image.width.lte:1920
Asserts that the input is an image and its width is less than or equal to the given width in pixels. Attribute:
ImageWidthLte::class
Method:
Validation::imageWidthLte(int $width)
066 Name: image.width.gte
Usage: image.width.gte:1920
Asserts that the input is an image and its width is greater than or equal to the given width in pixels. Attribute:
ImageWidthGte::class
Method:
Validation::imageWidthGte(int $width)
067 Name: image.height
Usage: image.height:1080
Asserts that the input is an image and its height is equal to the given height in pixels. Attribute:
ImageHeight::class
Method:
Validation::imageHeight(int $height)
068 Name: image.height.lte
Usage: image.height.lte:1080
Asserts that the input is an image and its height is less than or equal to the given height in pixels. Attribute:
ImageHeightLte::class
Method:
Validation::imageHeightLte(int $height)
069 Name: image.height.gte
Usage: image.height.gte:1080
Asserts that the input is an image and its height is greater than or equal to the given height in pixels. Attribute:
ImageHeightGte::class
Method:
Validation::imageHeightGte(int $height)
070 Name: image.dimensions
Usage: image.dimensions:1920,1080,==
Asserts that the input is an image and its dimensions are less than, equal to, or greater than the given width and height in pixels. Attribute:
ImageDimensions::class
Method:
Validation::imageDimensions(int $width, int $height, string $operator = '==')
071 Name: image.ratio
Usage: image.ratio:16:9
Asserts that the input is an image and its aspect ratio is equal to the given ratio (ratio must be specified as fraction like "16/9"). Attribute:
ImageRatio::class
Method:
Validation::imageRatio(string $ratio)
072 Name: if
Usage: if:7,7,==
Checks the condition between the first argument and the second argument, the condition operator can also be specified as the third argument. Attribute:
IfConstraint::class
Method:
Validation::if(mixed $actual, mixed $expected = true, string $operator = '==')
073 Name: if.eq
Usage: if.eq:3,3
Checks the condition between the first argument and the second argument, the condition operator is "==". Attribute:
IfEq::class
Method:
Validation::ifEq(mixed $actual, mixed $expected)
074 Name: if.neq
Usage: if.neq:1,2
Checks the condition between the first argument and the second argument, the condition operator is "!=". Attribute:
IfNeq::class
Method:
Validation::ifNeq(mixed $actual, mixed $expected)
075 Name: if.id
Usage: if.id:3,3
Checks the condition between the first argument and the second argument, the condition operator is "===". Attribute:
IfId::class
Method:
Validation::ifId(mixed $actual, mixed $expected)
076 Name: if.nid
Usage: if.nid:1,2
Checks the condition between the first argument and the second argument, the condition operator is "!==". Attribute:
IfNid::class
Method:
Validation::ifNid(mixed $actual, mixed $expected)
077 Name: if.gt
Usage: if.gt:2,1
Checks the condition between the first argument and the second argument, the condition operator is ">". Attribute:
IfGt::class
Method:
Validation::ifGt(mixed $actual, mixed $expected)
078 Name: if.gte
Usage: if.gte:2,2
Checks the condition between the first argument and the second argument, the condition operator is ">=". Attribute:
IfGte::class
Method:
Validation::ifGte(mixed $actual, mixed $expected)
079 Name: if.lt
Usage: if.lt:1,2
Checks the condition between the first argument and the second argument, the condition operator is "<". Attribute:
IfLt::class
Method:
Validation::ifLt(mixed $actual, mixed $expected)
080 Name: if.lte
Usage: if.lte:1,2
Checks the condition between the first argument and the second argument, the condition operator is "<=". Attribute:
IfLte::class
Method:
Validation::ifLte(mixed $actual, mixed $expected)
081 Name: empty
Usage: empty
Asserts that the input is empty using empty() language construct (is blank, i.e. empty string, empty array, false, null, or 0). Attribute:
EmptyConstraint::class
Method:
Validation::empty()
082 Name: required
Usage: required
Asserts that the input is required (is not blank, i.e. not a empty string or null). Attribute:
Required::class
Method:
Validation::required()
083 Name: allowed
Usage: allowed
Asserts that the input is allowed (can be empty or have any value, null and empty string are considered valid values). Attribute:
Allowed::class
Method:
Validation::allowed()
084 Name: forbidden
Usage: forbidden
Asserts that the input is forbidden (is null or not present). Attribute:
Forbidden::class
Method:
Validation::forbidden()
085 Name: accepted
Usage: accepted
Asserts that the input is accepted (equals: "on", "yes", "yeah", "yep", "yo", "ok", "okay", "aye", 1 or "1", true or "true") note that strings are treated in a case-insensitive manner. Attribute:
Accepted::class
Method:
Validation::accepted()
086 Name: declined
Usage: declined
Asserts that the input is declined (equals: "off", "no", "not", "nope", "neh", "nay", 0 or "0", false or "false") note that strings are treated in a case-insensitive manner. Attribute:
Declined::class
Method:
Validation::declined()
087 Name: bit
Usage: bit
Asserts that the input is bit (equals: 1 or "1", true; 0 or "0", false). Attribute:
Bit::class
Method:
Validation::bit()
088 Name: bit.isOn
Usage: bit.isOn
Asserts that the input is a turned on bit (equals: true, 1 or "1"). Attribute:
BitIsOn::class
Method:
Validation::bitIsOn()
089 Name: bit.isOff
Usage: bit.isOff
Asserts that the input is a turned off bit (equals: false, 0 or "0"). Attribute:
BitIsOff::class
Method:
Validation::bitIsOff()
090 Name: equals
Usage: equals:value
Asserts that the input is equal to the given value. Works with scalar types and null. Comparison operator is "==". Attribute:
Equals::class
Method:
Validation::equals(string|int|float|bool|null $value)
091 Name: matches
Usage: matches:'"/^[a-zA-Z0-9]+$/"'
Asserts that the input matches the given pattern. Works with strings only. Attribute:
Matches::class
Method:
Validation::matches(string $pattern)
092 Name: in
Usage: in:val1,val2,...
Asserts that the input is in the given values. Works with scalar types and null. Attribute:
In::class
Method:
Validation::in(string|int|float|bool|null ...$values)
093 Name: count
Usage: count:3
Asserts that the input count is equal to the given value. Works with all data types (null: 0; boolean: 0 or 1; float/integer: number value; string: characters count; array/countable: elements count; object: accessible properties count). Attribute:
Count::class
Method:
Validation::count(int $count)
094 Name: min
Usage: min:3
Asserts that the input count is greater than or equal to the given value. Works with all data types (null: 0; boolean: 0 or 1; float/integer: number value; string: characters count; array/countable: elements count; object: accessible properties count). Attribute:
Min::class
Method:
Validation::min(int|float $count)
095 Name: max
Usage: max:3
Asserts that the input count is less than or equal to the given value. Works with all data types (null: 0; boolean: 0 or 1; float/integer: number value; string: characters count; array/countable: elements count; object: accessible properties count). Attribute:
Max::class
Method:
Validation::max(int|float $count)
096 Name: between
Usage: between:3,7
Asserts that the input count is between the given values. Works with all data types (null: 0; boolean: 0 or 1; float/integer: number value; string: characters count; array/countable: elements count; object: accessible properties count). Attribute:
Between::class
Method:
Validation::between(int|float $min, int|float $max)
097 Name: number.isPositive
Usage: number.isPositive
Asserts that the input is a positive number. Attribute:
NumberIsPositive::class
Method:
Validation::numberIsPositive()
098 Name: number.isNegative
Usage: number.isNegative
Asserts that the input is a negative number. Attribute:
NumberIsNegative::class
Method:
Validation::numberIsNegative()
099 Name: number.isEven
Usage: number.isEven
Asserts that the input is an even number. Attribute:
NumberIsEven::class
Method:
Validation::numberIsEven()
100 Name: number.isOdd
Usage: number.isOdd
Asserts that the input is an odd number. Attribute:
NumberIsOdd::class
Method:
Validation::numberIsOdd()
101 Name: number.isMultipleOf
Usage: number.isMultipleOf:3
Asserts that the input is a multiple of the given number. Attribute:
NumberIsMultipleOf::class
Method:
Validation::numberIsMultipleOf(float $number)
102 Name: number.isFinite
Usage: number.isFinite
Asserts that the input is a finite number. Attribute:
NumberIsFinite::class
Method:
Validation::numberIsFinite()
103 Name: number.isInfinite
Usage: number.isInfinite
Asserts that the input is an infinite number. Attribute:
NumberIsInfinite::class
Method:
Validation::numberIsInfinite()
104 Name: number.isNan
Usage: number.isNan
Asserts that the input is a not a number. Attribute:
NumberIsNan::class
Method:
Validation::numberIsNan()
105 Name: string.charset
Usage: string.charset:UTF-8
Asserts that the input is encoded in one of the given charsets (aliases included). The check is done in a case-sensitive manner. Attribute:
StringCharset::class
Method:
Validation::stringCharset(string|array $charset)
106 Name: string.contains
Usage: string.contains:substring
Asserts that the input contains the given substring. A second boolean argument can be specified to enable strict mode (case-sensitive). Attribute:
StringContains::class
Method:
Validation::stringContains(string $substring, bool $strict = false)
107 Name: string.startsWith
Usage: string.startsWith:substring,1
Asserts that the input starts with the given substring. A second boolean argument can be specified to enable strict mode (case-sensitive). Attribute:
StringStartsWith::class
Method:
Validation::stringStartsWith(string $substring, bool $strict = false)
108 Name: string.endsWith
Usage: string.endsWith:substring,0
Asserts that the input ends with the given substring. A second boolean argument can be specified to enable strict mode (case-sensitive). Attribute:
StringEndsWith::class
Method:
Validation::stringEndsWith(string $substring, bool $strict = false)
109 Name: string.length
Usage: string.length:3
Asserts that the input is a string that is exactly the given length. Attribute:
StringLength::class
Method:
Validation::stringLength(int $length)
110 Name: string.wordsCount
Usage: string.wordsCount:3
Asserts that the input is a string containing exactly the given count of words. Attribute:
StringWordsCount::class
Method:
Validation::stringWordsCount(int $count)
111 Name: array.hasKey
Usage: array.hasKey:key
Asserts that the input array has the given key. Attribute:
ArrayHasKey::class
Method:
Validation::arrayHasKey(string|int $key)
112 Name: array.hasValue
Usage: array.hasValue:value
Asserts that the input array contains the given value. Works with scalar types. Attribute:
ArrayHasValue::class
Method:
Validation::arrayHasValue(mixed $value)
113 Name: array.hasDistinct
Usage: array.hasDistinct:key
Asserts that the input is a multidimensional array that contains distinct values of the given key. Attribute:
ArrayHasDistinct::class
Method:
Validation::arrayHasDistinct(string|int $key)
114 Name: array.isAssociative
Usage: array.isAssociative
Asserts that the input is an associative array. Attribute:
ArrayIsAssociative::class
Method:
Validation::arrayIsAssociative()
115 Name: array.isSequential
Usage: array.isSequential
Asserts that the input is a sequential array. Attribute:
ArrayIsSequential::class
Method:
Validation::arrayIsSequential()
116 Name: array.isUnique
Usage: array.isUnique
Asserts that the input array contains unique values. Works only with one-dimensional arrays. Attribute:
ArrayIsUnique::class
Method:
Validation::arrayIsUnique()
117 Name: array.subset
Usage: array.subset:'{"a":1,"b":2}'
Asserts that the input is an array that contains the given subset. Note that this check applies only to the first dimension of the array. Attribute:
ArraySubset::class
Method:
Validation::arraySubset(array $subset)
118 Name: object.hasProperty
Usage: object.hasProperty:property
Asserts that the input has the given property. Attribute:
ObjectHasProperty::class
Method:
Validation::objectHasProperty(string $property)
119 Name: object.hasMethod
Usage: object.hasMethod:method
Asserts that the input has the given method. Attribute:
ObjectHasMethod::class
Method:
Validation::objectHasMethod(string $method)
120 Name: object.isStringable
Usage: object.isStringable
Asserts that the input implements __toString() method. Attribute:
ObjectIsStringable::class
Method:
Validation::objectIsStringable()
121 Name: object.isInstanceOf
Usage: object.isInstanceOf:\Namespace\Class
Asserts that the input is an instance of the given class. Attribute:
ObjectIsInstanceOf::class
Method:
Validation::objectIsInstanceOf(string $classFQN)
122 Name: object.isSubclassOf
Usage: object.isSubclassOf:\Namespace\Class
Asserts that the input is a subclass of the given class. Attribute:
ObjectIsSubclassOf::class
Method:
Validation::objectIsSubclassOf(string $classFQN)
123 Name: serialized
Usage: serialized
Asserts that the input is a valid PHP serialized data. Attribute:
Serialized::class
Method:
Validation::serialized()
124 Name: json
Usage: json
Asserts that the input is a valid JSON. Attribute:
Json::class
Method:
Validation::json()
125 Name: base64
Usage: base64
Asserts that the input is a valid Base64 encoded string. Attribute:
Base64::class
Method:
Validation::base64()
126 Name: xml
Usage: xml
Asserts that the input is a valid XML. Attribute:
Xml::class
Method:
Validation::xml()
127 Name: locale
Usage: locale
Asserts that the input is a valid locale identifier (default: [ISO 639-1] or [ISO 639-1]_[ISO 3166-1 alpha-2], case-insensitive, input is canonicalized before checking (dashes to underscores, no dots or charset); strict: [ISO 639-1] or [ISO 639-1]_[ISO 3166-1 alpha-2], case-sensitive without canonicalization. Attribute:
Locale::class
Method:
Validation::locale(bool $strict = false)
128 Name: language
Usage: language
Asserts that the input is a valid language code (default: "ISO 639-1"; long: "ISO 639-2/T"). Attribute:
Language::class
Method:
Validation::language(bool $long = false)
129 Name: country
Usage: country
Asserts that the input is a valid country code (default: "ISO 3166-1 alpha-2"; long: "ISO 3166-1 alpha-3"). Attribute:
Country::class
Method:
Validation::country(bool $long = false)
130 Name: timezone
Usage: timezone
Asserts that the input is a valid timezone identifier (default: case-insensitive; strict: case-sensitive). Attribute:
Timezone::class
Method:
Validation::timezone(bool $strict = false)
131 Name: datetime
Usage: datetime
Asserts that the input is a valid datetime string/object. Attribute:
Datetime::class
Method:
Validation::datetime()
132 Name: datetime.eq
Usage: datetime.eq:"2015-01-01"
Asserts that the input is equal to the given datetime string. Attribute:
DatetimeEq::class
Method:
Validation::datetimeEq(string $datetime)
133 Name: datetime.lt
Usage: datetime.lt:tomorrow
Asserts that the input is a datetime string/object less than (before) the given datetime string. Attribute:
DatetimeLt::class
Method:
Validation::datetimeLt(string $datetime)
134 Name: datetime.lte
Usage: datetime.lte:tomorrow
Asserts that the input is a datetime string/object less than (before) or equal to the given datetime string. Attribute:
DatetimeLte::class
Method:
Validation::datetimeLte(string $datetime)
135 Name: datetime.gt
Usage: datetime.gt:today
Asserts that the input is a datetime string/object greater than (after) the given datetime string. Attribute:
DatetimeGt::class
Method:
Validation::datetimeGt(string $datetime)
136 Name: datetime.gte
Usage: datetime.gte:today
Asserts that the input is a datetime string/object greater than (after) or equal to the given datetime string. Attribute:
DatetimeGte::class
Method:
Validation::datetimeGte(string $datetime)
137 Name: datetime.birthday
Usage: datetime.birthday
Asserts that the input is a datetime string/object that has birthday today. Input should preferably be in "YYYY-MM-DD" format. Attribute:
DatetimeBirthday::class
Method:
Validation::datetimeBirthday()
138 Name: datetime.format
Usage: datetime.format:"Y-m-d H:i:s"
Asserts that the input is a valid date/time with the given format. Attribute:
DatetimeFormat::class
Method:
Validation::datetimeFormat(string $format)
139 Name: datetime.format.global
Usage: datetime.format.global
Asserts that the input looks like a valid global datetime string as defined in the HTML5 specification. Attribute:
DatetimeFormatGlobal::class
Method:
Validation::datetimeFormatGlobal()
140 Name: datetime.format.local
Usage: datetime.format.local
Asserts that the input looks like a valid local datetime string as defined in the HTML5 specification. Attribute:
DatetimeFormatLocal::class
Method:
Validation::datetimeFormatLocal()
141 Name: datestamp
Usage: datestamp
Asserts that the input looks like a human datestamp, DMY or MDY format, separated with dot, dash, or slash. Attribute:
Datestamp::class
Method:
Validation::datestamp()
142 Name: datestamp.ymd
Usage: datestamp.ymd
Asserts that the input looks like a human YMD-formatted datestamp, separated with dot, dash, or slash. Attribute:
DatestampYmd::class
Method:
Validation::datestampYmd()
143 Name: datestamp.dmy
Usage: datestamp.dmy
Asserts that the input looks like a human DMY-formatted datestamp, separated with dot, dash, or slash. Attribute:
DatestampDmy::class
Method:
Validation::datestampDmy()
144 Name: datestamp.mdy
Usage: datestamp.mdy
Asserts that the input looks like a human MDY-formatted datestamp, separated with dot, dash, or slash. Attribute:
DatestampMdy::class
Method:
Validation::datestampMdy()
145 Name: timestamp
Usage: timestamp
Asserts that the input looks like a human timestamp, 24 or 12 hours format with or without seconds. Attribute:
Timestamp::class
Method:
Validation::timestamp()
146 Name: timestamp.12
Usage: timestamp.12
Asserts that the input looks like a human timestamp, 12 hours format with or without seconds and optional AM/PM. Attribute:
Timestamp12::class
Method:
Validation::timestamp12()
147 Name: timestamp.hms
Usage: timestamp.hms
Asserts that the input looks like a human timestamp, 24 or 12 hours format with seconds. Attribute:
TimestampHms::class
Method:
Validation::timestampHms()
148 Name: timestamp.hm
Usage: timestamp.hm
Asserts that the input looks like a human timestamp, 24 or 12 hours format without seconds. Attribute:
TimestampHm::class
Method:
Validation::timestampHm()
149 Name: timestamp.ms
Usage: timestamp.ms
Asserts that the input looks like a human timestamp, containing minutes and seconds only. Attribute:
TimestampMs::class
Method:
Validation::timestampMs()
150 Name: calender.day
Usage: calender.day
Asserts that the input looks like a calendar dayin shot or long format ("Mon" or "Monday"). Attribute:
CalenderDay::class
Method:
Validation::calenderDay()
151 Name: calender.month
Usage: calender.month
Asserts that the input looks like a calendar month in shot or long format ("Jan" or "January"). Attribute:
CalenderMonth::class
Method:
Validation::calenderMonth()
152 Name: username
Usage: username
Asserts that the input is a valid username (between 4-32 characters, consists of letters in any case, optionally numbers, optionally one of the following characters "-_." (not consecutive), and must always start with a letter and end with a letter or number). Attribute:
Username::class
Method:
Validation::username()
153 Name: password
Usage: password
Asserts that the input is a valid password (minimum 8 characters, consists of at least one small letter and one capital letter, at least one number, at least one special character, and optionally a space). Attribute:
Password::class
Method:
Validation::password()
154 Name: uuid
Usage: uuid
Asserts that the input is a valid UUID. The version (v1/v2/v3/v4/v5) can be specifed to narrow the pattern. Attribute:
Uuid::class
Method:
Validation::uuid(string|int|null $version = null)
155 Name: ascii
Usage: ascii
Asserts that the input is a string containing only ASCII characters (ASCII compliant string). Attribute:
Ascii::class
Method:
Validation::ascii()
156 Name: slug
Usage: slug
Asserts that the input is a valid slug. Attribute:
Slug::class
Method:
Validation::slug()
157 Name: meta
Usage: meta
Asserts that the input is a string containing only meta characters (special characters) (i.e. "@, #, $, ...").. Attribute:
Meta::class
Method:
Validation::meta()
158 Name: text
Usage: text
Asserts that the input is a string containing letters and punctuation from any language. Attribute:
Text::class
Method:
Validation::text()
159 Name: words
Usage: words
Asserts that the input is a string containing only words and spaces without any other character. Attribute:
Words::class
Method:
Validation::words()
160 Name: spaceless
Usage: spaceless
Asserts that the input is a string containing no whitespace characters. Attribute:
Spaceless::class
Method:
Validation::spaceless()
161 Name: emoji
Usage: emoji
Asserts that the input contains an emoji. Attribute:
Emoji::class
Method:
Validation::emoji()
162 Name: roman
Usage: roman
Asserts that the input is a valid roman number. Attribute:
Roman::class
Method:
Validation::roman()
163 Name: phone
Usage: phone
Asserts that the input is a valid phone number (supports: North America, Europe and most Asian and Middle East countries). Attribute:
Phone::class
Method:
Validation::phone()
164 Name: geolocation
Usage: geolocation
Asserts that the input is a valid geolocation (latitude and longitude coordinates combination). Attribute:
Geolocation::class
Method:
Validation::geolocation()
165 Name: version
Usage: version
Asserts that the input is a valid semantic version number. Attribute:
Version::class
Method:
Validation::version()
166 Name: amount
Usage: amount
Asserts that the input contains only numbers, an optional decimal point (comma or dot), and an optional minus (used for amounts of money for example). Attribute:
Amount::class
Method:
Validation::amount()
167 Name: amount.dollar
Usage: amount.dollar
Asserts that the input is a validly formatted amount of USD, where decimal point and thousands separator are optional. Attribute:
AmountDollar::class
Method:
Validation::amountDollar()
168 Name: amount.euro
Usage: amount.euro
Asserts that the input is a validly formatted amount of EUR, where decimal point and thousands separator are optional. Attribute:
AmountEuro::class
Method:
Validation::amountEuro()
169 Name: color
Usage: color
Asserts that the input is a valid CSS color (Keyword "loose", HEX, HEX-Alpha, RGB, RGBA, RGB "new syntax", HSL, HSLA, HSL "new syntax"). Attribute:
Color::class
Method:
Validation::color()
170 Name: color.hex
Usage: color.hex
Asserts that the input is a valid CSS HEX color. Attribute:
ColorHex::class
Method:
Validation::colorHex()
171 Name: color.hexShort
Usage: color.hexShort
Asserts that the input is a valid CSS 3-Char-HEX color. Attribute:
ColorHexShort::class
Method:
Validation::colorHexShort()
172 Name: color.hexLong
Usage: color.hexLong
Asserts that the input is a valid CSS 6-Char-HEX color. Attribute:
ColorHexLong::class
Method:
Validation::colorHexLong()
173 Name: color.hexAlpha
Usage: color.hexAlpha
Asserts that the input is a valid CSS HEX-Alpha (4 or 8 Chars) color. Attribute:
ColorHexAlpha::class
Method:
Validation::colorHexAlpha()
174 Name: color.rgb
Usage: color.rgb
Asserts that the input is a valid CSS RGB color. Attribute:
ColorRgb::class
Method:
Validation::colorRgb()
175 Name: color.rgba
Usage: color.rgba
Asserts that the input is a valid CSS RGBA color. Attribute:
ColorRgba::class
Method:
Validation::colorRgba()
176 Name: color.rgb.new
Usage: color.rgb.new
Asserts that the input is a valid CSS4 RGB color. Attribute:
ColorRgbNew::class
Method:
Validation::colorRgbNew()
177 Name: color.hsl
Usage: color.hsl
Asserts that the input is a valid CSS HSL color. Attribute:
ColorHsl::class
Method:
Validation::colorHsl()
178 Name: color.hsla
Usage: color.hsla
Asserts that the input is a valid CSS HSLA color. Attribute:
ColorHsla::class
Method:
Validation::colorHsla()
179 Name: color.hsl.new
Usage: color.hsl.new
Asserts that the input is a valid CSS4 HSL color. Attribute:
ColorHslNew::class
Method:
Validation::colorHslNew()
180 Name: color.keyword
Usage: color.keyword
Asserts that the input is a valid CSS keyword color (strict, as in the CSS specification). Attribute:
ColorKeyword::class
Method:
Validation::colorKeyword()
181 Name: ssn
Usage: ssn
Asserts that the input is a valid SSN (US Social Security Number). Attribute:
Ssn::class
Method:
Validation::ssn()
182 Name: sin
Usage: sin
Asserts that the input is a valid SIN (CA Social Insurance Number). Attribute:
Sin::class
Method:
Validation::sin()
183 Name: nino
Usage: nino
Asserts that the input is a valid NINO (UK National Insurance Number). Attribute:
Nino::class
Method:
Validation::nino()
184 Name: vin
Usage: vin
Asserts that the input is a valid VIN (Vehicle Identification Number). Attribute:
Vin::class
Method:
Validation::vin()
185 Name: issn
Usage: issn
Asserts that the input is a valid ISSN (International Standard Serial Number). Attribute:
Issn::class
Method:
Validation::issn()
186 Name: isin
Usage: isin
Asserts that the input is a valid ISIN (International Securities Identification Number). Attribute:
Isin::class
Method:
Validation::isin()
187 Name: isbn
Usage: isbn
Asserts that the input is a valid ISBN (International Standard Book Number). The type (10/13) can be specifed to narrow the pattern. Attribute:
Isbn::class
Method:
Validation::isbn(string|int|null $type = null)
188 Name: imei
Usage: imei
Asserts that the input is a valid IMEI (International Mobile Station Equipment Identity Number). Attribute:
Imei::class
Method:
Validation::imei()
189 Name: imei.sv
Usage: imei.sv
Asserts that the input is a valid IMEI-SV (International Mobile Station Equipment Identity and Software Version Number). Attribute:
ImeiSv::class
Method:
Validation::imeiSv()
190 Name: meid
Usage: meid
Asserts that the input is a valid MEID (Mobile Equipment Identifier). Attribute:
Meid::class
Method:
Validation::meid()
191 Name: esn
Usage: esn
Asserts that the input is a valid ESN (Electronic Serial Number). Attribute:
Esn::class
Method:
Validation::esn()
192 Name: currency
Usage: currency
Asserts that the input is a valid currency code (default: "ISO 4217 alpha"; numeric: "ISO 4217 numeric"). Attribute:
Currency::class
Method:
Validation::currency(bool $numeric = false)
193 Name: currency.name
Usage: currency.name
Asserts that the input is a valid currency name (as in ISO 4217). Attribute:
CurrencyName::class
Method:
Validation::currencyName()
194 Name: creditcard
Usage: creditcard
Asserts that the input is a valid credit card number, balanced spaces and/or dashes are allowed. Attribute:
Creditcard::class
Method:
Validation::creditcard()
195 Name: creditcard.visa
Usage: creditcard.visa
Asserts that the input is a valid Visa credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardVisa::class
Method:
Validation::creditcardVisa()
196 Name: creditcard.mastercard
Usage: creditcard.mastercard
Asserts that the input is a valid Mastercard credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardMastercard::class
Method:
Validation::creditcardMastercard()
197 Name: creditcard.discover
Usage: creditcard.discover
Asserts that the input is a valid Discover credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardDiscover::class
Method:
Validation::creditcardDiscover()
198 Name: creditcard.americanExpress
Usage: creditcard.americanExpress
Asserts that the input is a valid American Express credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardAmericanExpress::class
Method:
Validation::creditcardAmericanExpress()
199 Name: creditcard.dinersClub
Usage: creditcard.dinersClub
Asserts that the input is a valid Diners Club credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardDinersClub::class
Method:
Validation::creditcardDinersClub()
200 Name: creditcard.jcb
Usage: creditcard.jcb
Asserts that the input is a valid JCB credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardJcb::class
Method:
Validation::creditcardJcb()
201 Name: creditcard.maestro
Usage: creditcard.maestro
Asserts that the input is a valid Maestro credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardMaestro::class
Method:
Validation::creditcardMaestro()
202 Name: creditcard.chinaUnionPay
Usage: creditcard.chinaUnionPay
Asserts that the input is a valid China UnionPay credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardChinaUnionPay::class
Method:
Validation::creditcardChinaUnionPay()
203 Name: creditcard.instaPayment
Usage: creditcard.instaPayment
Asserts that the input is a valid InstaPayment credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardInstaPayment::class
Method:
Validation::creditcardInstaPayment()
204 Name: creditcard.laser
Usage: creditcard.laser
Asserts that the input is a valid Laser credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardLaser::class
Method:
Validation::creditcardLaser()
205 Name: creditcard.uatp
Usage: creditcard.uatp
Asserts that the input is a valid UATP credit card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardUatp::class
Method:
Validation::creditcardUatp()
206 Name: creditcard.mir
Usage: creditcard.mir
Asserts that the input is a valid MIR Payment System card number, balanced spaces and/or dashes are allowed. Attribute:
CreditcardMir::class
Method:
Validation::creditcardMir()
207 Name: cvv
Usage: cvv
Asserts that the input is a valid CVV (Card Security Code). Attribute:
Cvv::class
Method:
Validation::cvv()
208 Name: bic
Usage: bic
Asserts that the input is a valid BIC (Bank Identifier Code). Attribute:
Bic::class
Method:
Validation::bic()
209 Name: iban
Usage: iban:IQ
Asserts that the input is a valid IBAN (International Bank Account Number). The "ISO 3166-1 alpha-2" country code can be specifed to narrow the pattern. Attribute:
Iban::class
Method:
Validation::iban(?string $country = null)
210 Name: luhn
Usage: luhn
Asserts that the input passes the Luhn Algorithm check. This rule is mostly used in conjunction with other rules like credit card numbers and identifiers to further check the validity of the subject. Attribute:
Luhn::class
Method:
Validation::luhn()
211 Name: php.keyword
Usage: php.keyword
Asserts that the input is a PHP language keyword. Attribute:
PhpKeyword::class
Method:
Validation::phpKeyword()
212 Name: php.reserved
Usage: php.reserved
Asserts that the input is a PHP language reserved word. Attribute:
PhpReserved::class
Method:
Validation::phpReserved()
213 Name: php.reserved.extra
Usage: php.reserved.extra
Asserts that the input is a PHP language reserved word including soft reserved words. Attribute:
PhpReservedExtra::class
Method:
Validation::phpReservedExtra()
214 Name: regex
Usage: regex
Asserts that the input is a valid regular expression. Attribute:
Regex::class
Method:
Validation::regex()
215 Name: bool
Usage: see boolean
Alias, refer to boolean for the full description. Attribute:
BoolConstraint::class
Method:
Validation::bool()
216 Name: int
Usage: see integer
Alias, refer to integer for the full description. Attribute:
IntConstraint::class
Method:
Validation::int()
217 Name: long
Usage: see integer
Alias, refer to integer for the full description. Attribute:
Long::class
Method:
Validation::long()
218 Name: double
Usage: see float
Alias, refer to float for the full description. Attribute:
Double::class
Method:
Validation::double()
219 Name: real
Usage: see float
Alias, refer to float for the full description. Attribute:
Real::class
Method:
Validation::real()
220 Name: str
Usage: see string
Alias, refer to string for the full description. Attribute:
Str::class
Method:
Validation::str()
221 Name: arr
Usage: see array
Alias, refer to array for the full description. Attribute:
Arr::class
Method:
Validation::arr()
222 Name: obj
Usage: see object
Alias, refer to object for the full description. Attribute:
Obj::class
Method:
Validation::obj()
223 Name: stream
Usage: see resource
Alias, refer to resource for the full description. Attribute:
Stream::class
Method:
Validation::stream()
224 Name: assert
Usage: see if
Alias, refer to if for the full description. Attribute:
Assert::class
Method:
Validation::assert(mixed $actual, mixed $expected = true, string $operator = '==')
225 Name: assert.equals
Usage: see if.eq
Alias, refer to if.eq for the full description. Attribute:
AssertEquals::class
Method:
Validation::assertEquals(mixed $actual, mixed $expected)
226 Name: assert.notEquals
Usage: see if.neq
Alias, refer to if.neq for the full description. Attribute:
AssertNotEquals::class
Method:
Validation::assertNotEquals(mixed $actual, mixed $expected)
227 Name: assert.greaterThan
Usage: see if.gt
Alias, refer to if.gt for the full description. Attribute:
AssertGreaterThan::class
Method:
Validation::assertGreaterThan(mixed $actual, mixed $expected)
228 Name: assert.greaterThanOrEquals
Usage: see if.gte
Alias, refer to if.gte for the full description. Attribute:
AssertGreaterThanOrEquals::class
Method:
Validation::assertGreaterThanOrEquals(mixed $actual, mixed $expected)
229 Name: assert.lessThan
Usage: see if.lt
Alias, refer to if.lt for the full description. Attribute:
AssertLessThan::class
Method:
Validation::assertLessThan(mixed $actual, mixed $expected)
230 Name: assert.lessThanOrEquals
Usage: see if.lte
Alias, refer to if.lte for the full description. Attribute:
AssertLessThanOrEquals::class
Method:
Validation::assertLessThanOrEquals(mixed $actual, mixed $expected)
231 Name: blank
Usage: see empty
Alias, refer to empty for the full description. Attribute:
Blank::class
Method:
Validation::blank()
232 Name: is
Usage: see equals
Alias, refer to equals for the full description. Attribute:
Is::class
Method:
Validation::is(mixed $value)
233 Name: same
Usage: see equals
Alias, refer to equals for the full description. Attribute:
Same::class
Method:
Validation::same(mixed $value)
234 Name: pattern
Usage: see matches
Alias, refer to matches for the full description. Attribute:
Pattern::class
Method:
Validation::pattern(string $pattern)
235 Name: choice
Usage: see in
Alias, refer to in for the full description. Attribute:
Choice::class
Method:
Validation::choice(string|int|float|bool|null ...$values)
236 Name: size
Usage: see count
Alias, refer to count for the full description. Attribute:
Size::class
Method:
Validation::size(int $size)
237 Name: length
Usage: see count
Alias, refer to count for the full description. Attribute:
Length::class
Method:
Validation::length(int $count)
238 Name: range
Usage: see between
Alias, refer to between for the full description. Attribute:
Range::class
Method:
Validation::range(int|float $min, int|float $max)
239 Name: minmax
Usage: see between
Alias, refer to between for the full description. Attribute:
Minmax::class
Method:
Validation::minmax(int|float $min, int|float $max)
240 Name: filled
Usage: see required
Alias, refer to required for the full description. Attribute:
Filled::class
Method:
Validation::filled()
241 Name: present
Usage: see required
Alias, refer to required for the full description. Attribute:
Present::class
Method:
Validation::present()
242 Name: optional
Usage: see allowed
Alias, refer to allowed for the full description. Attribute:
Optional::class
Method:
Validation::optional()
243 Name: date
Usage: see datetime
Alias, refer to datetime for the full description. Attribute:
Date::class
Method:
Validation::date()
244 Name: date.equals
Usage: see datetime.eq
Alias, refer to datetime.eq for the full description. Attribute:
DateEquals::class
Method:
Validation::dateEquals(string $datetime)
245 Name: date.before
Usage: see datetime.lt
Alias, refer to datetime.lt for the full description. Attribute:
DateBefore::class
Method:
Validation::dateBefore(string $datetime)
246 Name: date.beforeOrEquals
Usage: see datetime.lte
Alias, refer to datetime.lte for the full description. Attribute:
DateBeforeOrEquals::class
Method:
Validation::dateBeforeOrEquals(string $datetime)
247 Name: date.after
Usage: see datetime.gt
Alias, refer to datetime.gt for the full description. Attribute:
DateAfter::class
Method:
Validation::dateAfter(string $datetime)
248 Name: date.afterOrEquals
Usage: see datetime.gte
Alias, refer to datetime.gte for the full description. Attribute:
DateAfterOrEquals::class
Method:
Validation::dateAfterOrEquals(string $datetime)
249 Name: date.format
Usage: see datetime.format
Alias, refer to datetime.format for the full description. Attribute:
DateFormat::class
Method:
Validation::dateFormat(string $format)
250 Name: cakeday
Usage: see datetime.birthday
Alias, refer to datetime.birthday for the full description. Attribute:
Cakeday::class
Method:
Validation::cakeday()

Macros

Macro Validation Expression
[nullable] null^~empty
[alnumDash] matches:"/[a-zA-Z0-9-_]+/"
[twitterHandle] matches:'\"/^[a-zA-Z_]{1}[a-zA-Z0-9_]{0,14}$/\"'
[gmail] email&string.contains:"@gmail."
[eduMail] email&string.endsWith:".edu"

Benchmarks

By now it may seem like Mighty is doing too much and performance concerns are starting to arise. Well, there is no need to worry about that. Mighty is really fast and is optimized to provide the best performance. Here are some benchmarks of the performance of the validator:

Not So Scientific Benchmark

The performance of Mighty Validator and Laravel Validator in a laravel application. The test was carried out using an array of 50000 elements, half of them are integers and the other half are numeric strings. Each validator was tested 10 times (consecutively) and the average result of these 10 was collected:

$data = array_merge(range(1, 25000), array_map('strval', range('25001', '50000')));
// Mighty Validator with XDebug disabled
[ // required&integer
  'preparationTime' => '1.32ms',    // the time required to build the array
  'validationTime'  => '1107.29ms', // the time required to validate the array
  'totalTime'       => '1108.61ms', // the time required for the whole process
]
// Mighty Validator with XDebug enabled
 [ // required&integer
  'preparationTime' => '9.09ms',
  'validationTime'  => '6085.04ms',
  'totalTime'       => '6094.13ms',
]
// Laravel Validator with XDebug disabled
[ // required|integer
  'preparationTime' => '1.33ms',
  'validationTime'  => '13882.72ms',
  'totalTime'       => '13884.05ms',
]
// Laravel Validator with XDebug enabled
[ // required|integer
  'preparationTime' => '9.33ms',
  'validationTime'  => '24010.60ms',
  'totalTime'       => '24019.93ms',
]

So Mighty is about 12.5X times faster than Laravel Validator with XDebug disabled and about 4X times faster with XDebug enabled.

Scientific Benchmark

The benchmark is done using PHPBench. Here is a quick overview:

PHPBench (1.2.6) running benchmarks...
with configuration file: mighty/phpbench.json.dist
with PHP version 8.1.9, xdebug ❌, opcache ❌

\MAKS\Mighty\Benchmarks\ConstraintBench

    benchAValidValidatableObject............I4 ✔ Mo305.595074ops/s (±0.75%)
    benchAnInvalidValidatableObject.........I4 ✔ Mo326.708522ops/s (±1.02%)

\MAKS\Mighty\Benchmarks\ValidatorBench

    benchSingleValidationString.............I4 ✔ Mo0.02212ms (±1.59%)
    benchSingleValidationObject.............I4 ✔ Mo0.126929ms (±1.63%)
    benchBulkValidationObject...............I4 ✔ Mo9.345847ms (±0.62%)
    benchBulkValidationString...............I4 ✔ Mo6.734188ms (±0.40%)

Subjects: 6, Assertions: 6, Failures: 0, Errors: 0

■ Fact: The most recent benchmark result can also be found in the CI pipeline, which will be updated with each Push/PR to the upsteam.


Notes

  1. Mighty generates really friendly error messages by default (currently only in English). These messages can be easily overwritten on Validator/Constraint bases. You may want to have these messages in different languages, for that, the MAKS\Mighty\Rule::setMessageTranslator() method can be used. This method is a convenient way to set a global message translator, it takes a closure that gets the raw message (with placeholders) as an argument and must return the translated version of that message.
  2. Refer to the Mighty Validation Expression Language Specification to learn more about the theory behind Mighty and to get a grasp of how the language works.
  3. Refer to Mighty API Documentation to learn more about the PHP API. The API is well-documented and there shouldn't be anything that is not covered there.
  4. Mighty is currently a pure validation library, it doesn't do any kind of transformation on the data. The engine and the current design is flexible enough and can be used to easily implement a Sanitizer on top of it, there is no plan to make this at the moment but it may be a future milestone.

License

Mighty is an open-source project licensed under the MIT license.
Copyright (c) 2022 Marwan Al-Soltany. All rights reserved.