PHP code example of yiisoft / hydrator-validator

1. Go to this page and download the library: Download yiisoft/hydrator-validator 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/ */

    

yiisoft / hydrator-validator example snippets


use Yiisoft\Hydrator\Validator\Attribute\Validate;
use Yiisoft\Hydrator\Validator\ValidatedInputInterface;
use Yiisoft\Hydrator\Validator\ValidatedInputTrait;
use Yiisoft\Validator\Rule\Email;
use Yiisoft\Validator\Rule\Required;

final class InputDto implements ValidatedInputInterface 
{
    use ValidatedInputTrait;
    
    #[Email]
    private string $email;
    
    #[Validate(new Required())]
    private string $name;
}

use Psr\Http\Message\RequestInterface;
use Yiisoft\Hydrator\Validator\ValidatingHydrator;

public function actionEdit(RequestInterface $request, ValidatingHydrator $hydrator): ResponseInterface
{
    $data = $request->getParsedBody();    
    $inputDto = $hydrator->create(InputDto::class, $data);
    
    if (!$inputDto->getValidationResult()->isValid()) {
        // Validation didn't pass :(
    }
    
    // Everything is fine. You can use $inputDto now.    
}