PHP code example of romagny13 / php-validator

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

    

romagny13 / php-validator example snippets




use PHPValidator\Helpers\Validations;
use PHPValidator\Helpers\Validator;

'password' => $password,
    'confirm_password' => 'xyz'
];

$validations = [
    'username' => [Validations::value) use($password){
        return $value === $password;
    },'Password and confirm password do not match.')]
];

$result = Validator::validateModel($validations, $model);
var_dump($result->hasError, $result->errors);


class NumberValidation extends Validation
{
    public function __construct($message)
    {
        $this->message = $message;
    }

    public function __invoke($value)
    {
        // if has no value => don't evaluate (this is the job of 

class MyValidations extends Validations
{
    public static function isNumeric($message='Please fix this field.'){
      return new NumberValidation($message);
    }
}

$model = [
    'username' => 'abcdefg',
    'age' => 'my age'
];

$validations = [
    'username' => [Validations::tions, $model);

class MyApplicationValidationService
{
    protected $validationService;
    protected $strategy;

    public function __construct(ValidationServiceInterface $validationService, ValidationStrategyInterface $strategy)
    {
        // allows to register validations by models and validate model values
        $this->validationService = $validationService;

        // returns Validation class instances (RequiredValidation, MinLengthValidation, etc.)
        $this->strategy = $strategy;

        // init
        $this->addPostValidations(); // post
        // other model Validations  (example category, user, ....)
    }

    public function addPostValidations(){
        $validations = [
            'title' => [$this->strategy->

// inject the services
$service = new MyApplicationValidationService(new ValidationService(), new ValidationStrategy());

// the model to validate
$post = [
    'title' => '',
    'content' => 'My content'
];
// and finally validate with the service
$result = $service->validatePost($post);
//
var_dump($result->hasError,$result->errors);
// easy to inject the errors in view
// for this example we have an error => $result->errors['title'] = 'This field is 

composer