PHP code example of componenta / validation

1. Go to this page and download the library: Download componenta/validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

componenta / validation example snippets


use Componenta\Validation\Rule\RuleFactory;
use Componenta\Validation\Validator;

$ruleFactory = new RuleFactory();

$validator = new Validator([
    'email' => $ruleFactory->createRule('ors = $result->toArray();
}

$validator = $factory->createFrom([
    'email' => '

$result = $validator->validate(['email' => 'invalid']);

if ($result !== true) {
    $result->has('email');
    $result->get('email');
    $result->toArray();
}

$validator = $factory->createFrom([
    'user.email' => ' 'string|length:1,50',
]);

$ruleFactory->createRule('email');
$ruleFactory->createRule('eateRule('oneof:email,phone');

use Componenta\Validation\Attribute\Field;
use Componenta\Validation\Attribute\Validate;
use Componenta\Validation\Attribute\When;
use Componenta\Validation\Rule\Email;
use Componenta\Validation\Rule\Required;

final class CreateUserCommand
{
    #[Field('user_email')]
    #[Required]
    #[Email]
    #[Validate('length:5,255')]
    public string $email;

    #[When('status:published', then: '

use Componenta\Validation\ContextInterface;
use Componenta\Validation\Error\ErrorMessage;
use Componenta\Validation\Error\ErrorMessageCollector;
use Componenta\Validation\Error\ErrorMessageCollectorInterface;
use Componenta\Validation\Rule\RuleInterface;

final class Uppercase implements RuleInterface
{
    public string $name {
        get => 'uppercase';
    }

    public function validate(mixed $value, ContextInterface $context): true|ErrorMessageCollectorInterface
    {
        if (is_string($value) && $value === strtoupper($value)) {
            return true;
        }

        $collector = new ErrorMessageCollector();
        $collector->add(
            (string) $context->getAttribute(ContextInterface::CURRENT_PATH_ATTRIBUTE, ''),
            new ErrorMessage($context, 'validation.uppercase.invalid'),
        );

        return $collector;
    }
}

$ruleFactory->register('uppercase', static fn (): RuleInterface => new Uppercase());
$ruleFactory->alias('upper', 'uppercase');

use Componenta\Validation\Context;
use Componenta\Validation\ContextInterface;

$context = new Context([
    ContextInterface::STOP_ON_FIRST_FAILURE_ATTRIBUTE => true,
    ContextInterface::THROW_ON_FAILURE_ATTRIBUTE => true,
]);