All Projects → franzose → kontrolio

franzose / kontrolio

Licence: MIT license
Simple standalone data validation library inspired by Laravel and Symfony

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to kontrolio

Validation
The power of Respect Validation on Laravel
Stars: ✭ 188 (+268.63%)
Mutual labels:  validator
Clamav Validator
Laravel virus validator based on ClamAV anti-virus scanner
Stars: ✭ 224 (+339.22%)
Mutual labels:  validator
finspec-spec
Multi-protocol, machine-readable specifications for financial services
Stars: ✭ 18 (-64.71%)
Mutual labels:  validator
Xmlschema
XML Schema validator and data conversion library for Python
Stars: ✭ 201 (+294.12%)
Mutual labels:  validator
Routinator
An RPKI Validator written in Rust
Stars: ✭ 215 (+321.57%)
Mutual labels:  validator
another-json-schema
Another JSON Schema validator, simple & flexible & intuitive.
Stars: ✭ 48 (-5.88%)
Mutual labels:  validator
Ajv Errors
Custom error messages in JSON-Schema for Ajv
Stars: ✭ 185 (+262.75%)
Mutual labels:  validator
gulp-html
Gulp plugin for HTML validation, using the official Nu Html Checker (v.Nu)
Stars: ✭ 70 (+37.25%)
Mutual labels:  validator
Copper
A configuration file validator for Kubernetes.
Stars: ✭ 223 (+337.25%)
Mutual labels:  validator
ngx-translate-lint
Simple CLI tools for check `ngx-translate` keys
Stars: ✭ 25 (-50.98%)
Mutual labels:  validator
Email address
The EmailAddress Gem to work with and validate email addresses.
Stars: ✭ 199 (+290.2%)
Mutual labels:  validator
Validr
A simple, fast, extensible python library for data validation.
Stars: ✭ 205 (+301.96%)
Mutual labels:  validator
rust-phonenumber
Library for parsing, formatting and validating international phone numbers.
Stars: ✭ 99 (+94.12%)
Mutual labels:  validator
Validot
Validot is a performance-first, compact library for advanced model validation. Using a simple declarative fluent interface, it efficiently handles classes, structs, nested members, collections, nullables, plus any relation or combination of them. It also supports translations, custom logic extensions with tests, and DI containers.
Stars: ✭ 198 (+288.24%)
Mutual labels:  validator
cron-validate
A cron-expression validator for TypeScript/JavaScript projects.
Stars: ✭ 40 (-21.57%)
Mutual labels:  validator
Ajv Keywords
Custom JSON-Schema keywords for Ajv validator
Stars: ✭ 186 (+264.71%)
Mutual labels:  validator
Stringformatter
Simple Text Formetter (Credit Card Number, Phone Number, Serial Number etc.) Can be used in all text inputs according to the format pattern. If desired, large minor character restrictions can be made in the format pattern.
Stars: ✭ 231 (+352.94%)
Mutual labels:  validator
djburger
Framework for safe and maintainable web-projects.
Stars: ✭ 75 (+47.06%)
Mutual labels:  validator
garn-validator
Create validations with ease
Stars: ✭ 42 (-17.65%)
Mutual labels:  validator
guice-validator
Guice javax.validation method validation integration
Stars: ✭ 35 (-31.37%)
Mutual labels:  validator

CI

На русском

Kontrolio: keep your data under control.

Kontrolio is a simple standalone data validation library inspired by Laravel and Symfony and compatible with PHP 8.1+. [ Read on Medium ]

Setting up validator

The best way to set up validator:

// In container unaware environments
$valid = Factory::getInstance()->make($data, $rules, $messages)->validate();

// Using a service container implementation
$container->singleton('validation', static fn() => new Factory());
$container->get('validation')->make($data, $rules, $messages)->validate();

Of course, you can use Kontrolio\Validator class directly but then you'll need to provide available validation rules by yourself:

$validator = new Validator($data, $rules, $messages)->extend($custom)->validate();

Data here is supposed to be the key-value pairs—attributes and their values:

$data = [
    'foo' => 'bar',
    'bar' => 'baz',
    'baz' => 'taz'
];

Validation rules can be set in three different formats:

  1. Laravel-like string
  2. Instances of the class based rules
  3. Callables (closures or callbacks)

You can also mix instances and callables when you set multiple validation rules to a single attribute. Here's a simple example:

$rules = [
    'one' => 'not_empty|length:5,15',
    'two' => new Email,
    'three' => static fn ($value) => $value === 'taz',
    'four' => [
        static fn ($value) => is_numeric($value),
        new GreaterThan(5),
    ]
];

When you set validation rules as string, validator will parse it to an ordinary array of rules before applying them to the attribute, so when you write 'some' => 'not_empty|length:5,15', it becomes

'some' => [
    new NotEmpty,
    new Length(5, 15)
]

It's pretty straightforward but remember that all arguments you pass after semicolon (separating them by commas) become the arguments of the validation rule constructor.

When you set validation rule as callback, internally it is wrapped by special object called Kontrolio\Rules\CallbackRuleWrapper to keep consistency defined by Kontrolio\Rules\RuleInterface interface.

Rule options

Allowing empty value

A single rule validation can be skipped when the validated attribute value is empty. If you feel that you need this option, you instantiate a rule using named constructor allowingEmptyValue() or by calling allowEmptyValue() method on the already existing instance:

'some' => [
    MyRule::allowingEmptyValue(),
    // (new MyRule())->allowEmptyValue()
]

Skipping rule validation

When creating a new custom class based rule you might need an option to skip its validation based on some conditions. You can define the behavior using canSkipValidation() method:

class MyRule extends AbstractRule
{
    public function canSkipValidation($input = null)
    {
        return $input === 'bar';
    }

    // ...
}

Callable rules

Callable rule is nothing more than a closure or function that takes an attribute value and returns either boolean result of the validation or an options array equivalent to options provided by a class based validation rule:

    'foo' => static fn ($value) => is_string($value),
    'bar' => static function ($value) {
        return [
            // required when array
            'valid' => $value === 'taz',
            
            // optionals
            'name' => 'baz', // rule identifier
            'empty_allowed' => true, // allowing empty value
            'skip' => false // don't allow skipping current rule validation,
            'violations' => [] // rule violations
        ];
    }

Custom rules

Of course you can create your custom rules. Just remember that each rule must be an instance of Kontrolio\Rules\RuleInterface, implement isValid() method and have an identifier. By default, identifiers are resolved by Kontrolio\Rules\AbstractRule and are based on the rule class name without namespace. However, you can override this behavior if you wish overriding getName() method.

Custom rules can be added eighter via factory or validator itself:

$factory = (new Factory())->extend([CustomRule::class]);

// with a custom identifier
$factory = (new Factory())->extend(['some_custom' => CustomRule::class]);
$validator = $factory->make([], [], []);

// if you don't use factory
$validator = new Validator([], [], []);
$validator->extend([CustomRule::class]);

// with a custom identifier
$validator->extend(['custom' => CustomRule::class]);
$validator->validate();

Bypassing attribute's value validation completely

It's not the same as using allowEmptyValue() or canSkipValidation() on a rule. With those you can skip only a rule. But you can also bypass a whole attribute by using Kontrolio\Rules\Core\Sometimes rule. Sometimes tells validator to bypass validation when the value of the attribute is null or empty. That's all. You can prepend Sometimes to the attribute's rules array or use its identifier in a ruleset string:

$rules = [
    'one' => 'sometimes|length:5,15',
    // 'one' => [
    //     new Sometimes(),
    //     new Length(5, 15)
    // ]
];

Stopping validation on the first failure

You can tell the validator to stop validation if any validation error occurs:

$validator->shouldStopOnFailure()->validate();

Stopping certain attribute's validation on the first failure

Using UntilFirstFailure validation rule, you can also stop validation of a single attribute while keeping validation as a whole:

$data = [
    'attr' => '',
    'attr2' => 'value2'
];

$rules = [
    'attr' => [
        new UntilFirstFailure(),
        new NotBlank(),
        new NotFooBar()
    ]
];

$messages = [<...>];

$validator = new Validator($data, $rules, $messages)->validate();

Now when attr fail with NotBlank rule, its validation will be stopped and validator will proceed to the attr2.

Error messages and rule violations

Error messages has a single simple format you'll love:

$messages = [
    'foo' => 'Foo cannot be null',
    'foo.length' => 'Wrong length of foo',
    'foo.length.min' => 'Foo is less than 3'
    // '[attribute].[rule].[violation]
];

Every message key can have three segments separated by dot. They are:

  1. Attribute name
  2. Validation rule identifier
  3. Validation rule violation

With these options you can customize messages from the most general to the most specific. Each violation is set by the rule validating the attribute value. So when writing your own validation rule you may provide your own violations to provide customizability of the validation result and error messages.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].