PHP code example of longdinhh / validation

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

    

longdinhh / validation example snippets




occoc\Validation\Factory;

$validation = (new Factory)->make($_POST + $_FILES, [
    'name'                  => ''      => '           => '$validation->errors();
    echo "<pre>";
    print_r($errors->firstOfAll());
    echo "</pre>";
    exit;
} else {
    // validation passes
    echo "Success!";
}



occoc\Validation\Factory;

$validation = (new Factory)->validate($_POST + $_FILES, [
    'name'                  => '   => '           => 'pre>";
	print_r($errors->firstOfAll());
	echo "</pre>";
	exit;
} else {
	// validation passes
	echo "Success!";
}

use Coccoc\Validation\Factory;

$validation = (new Factory)->make([
	'province_id' => $_POST['province_id'],
	'district_id' => $_POST['district_id']
], [
	'province_id:Province' => 'n validate it
$validation->validate();

use Coccoc\Validation\Factory;

$factory = new Factory();
$factory->messages()->add('es', [
    'rule.

use Coccoc\Validation\Factory;

$factory = new Factory();
$factory->messages()->replace('en', 'rule.

use Coccoc\Validation\Factory;

$factory = new Factory();
$factory->messages()->default('es');

$validation = $factory->validate($inputs, $rules);
$validation->validate();

use Coccoc\Validation\Factory;

$validator = new Factory();
$validation_a = $validator->make($input, [
	'age' => '

use Coccoc\Validation\Factory;

$validator = new Factory();
$validation_a = $validator->make($input, [
	'age' => '

use Coccoc\Validation\Factory;

$validation = (new Factory())->validate($inputs, $rules);

$errors = $validation->errors();

$messages = $errors->all();
// [
//     'email is not a valid email address',
//     'password minimum is 6 characters',
//     'password must contain capital letters'
// ]

$messages = $errors->all('<li>:message</li>');
// [
//     '<li>email is not a valid email address</li>',
//     '<li>password minimum is 6 character</li>',
//     '<li>password must contain capital letters</li>'
// ]

$messages = $errors->firstOfAll();
// [
//     'email' => Email is not valid email',
//     'password' => 'Password minimum 6 character',
// ]

$messages = $errors->firstOfAll('<li>:message</li>');
// [
//     'email' => '<li>Email is not valid email</li>',
//     'password' => '<li>Password minimum 6 character</li>',
// ]

$messages = $errors->firstOfAll(':message', false);
// [
//     'contacts' => [
//          1 => [
//              'email' => 'Email is not valid email',
//              'phone' => 'Phone is not valid phone number'
//          ],
//     ],
// ]

$messages = $errors->firstOfAll(':message', true);
// [
//     'contacts.1.email' => 'Email is not valid email',
//     'contacts.1.phone' => 'Email is not valid phone number',
// ]

if ($emailError = $errors->first('email')) {
    echo $emailError;
}

$messages = $errors->toArray();
// [
//     'email' => [
//         'email' => 'Email is not valid email'
//     ],
//     'password' => [
//         'min' => 'Password minimum 6 character',
//         'regex' => Password must contains capital letters'
//     ]
// ]

$message = $errors->toDataBag()->filter()->first();

use Coccoc\Validation\Factory;

$validation = (new Factory())->validate([
    'title' => 'Lorem Ipsum',
    'body' => 'Lorem ipsum dolor sit amet ...',
    'published' => null,
    'something' => '-invalid-'
], [
    'title' => '

$validatedData = $validation->getValidatedData();
// [
//     'title' => 'Lorem Ipsum',
//     'body' => 'Lorem ipsum dolor sit amet ...',
//     'published' => '1' // notice this
//     'something' => '-invalid-'
// ]

$validData = $validation->getValidData();
// [
//     'title' => 'Lorem Ipsum',
//     'body' => 'Lorem ipsum dolor sit amet ...',
//     'published' => '1'
// ]

$invalidData = $validation->getInvalidData();
// [
//     'something' => '-invalid-'
// ]

use Coccoc\Validation\Factory;
use Coccoc\Validation\Rules\AnyOf;

$validation = $factory->validate([
    'field' => 'foo;bar;example'
], [
    'field' => $factory->rule('any_of')->separator(';')->values(['foo', 'bar']),
]);

$validation->passes(); // true if field only contains the values in any_of

$validation = $validator->validate([
    'photo' => $_FILES['photo']
], [
    'photo' => '

$validation = $validator->validate($_POST, [
    'even_number' => [
        'n (is_numeric($value) AND $value % 2 === 0);
        },
        'callback' => fn ($v) => is_numeric($v) && $v % 2 === 0,
    ]
]);

$validation = $validator->validate($_POST, [
    'even_number' => [
        '       return ":attribute must be numeric.";
            }
            if ($value % 2 !== 0) {
                return ":attribute is not even number.";
            }
            
            return true; // always return true if validation passes
        }
    ]
]);

use Coccoc\Validation\Factory;

$validation = (new Factory)->validate([
    'enabled' => null
], [
    'enabled' => 'default:1|= $validation->getValidData();

$enabled = $valid_data['enabled'];
$published = $valid_data['published'];

use Coccoc\Validation\Factory;

$validation = (new Factory)->validate([
    'country' => 'GBR'
], [
    'country' => 'exists:countries,id',
]);

$validation->passes(); // true if table countries has a record with id GBR

use Doctrine\DBAL\Query\QueryBuilder;
use Coccoc\Validation\Factory;
use Coccoc\Validation\Rules\Exists;

$factory    = new Factory;
$factory->addRule('exists', new Exists($dbalConn));

$validation = $factory->validate([
    'country' => 'GBR'
], [
    'country' => $factory->rule('exists')->table('countries')->column('id')->where(fn (QueryBuilder $qb) => $qb->andWhere('active = 1')),
]);

$validation->passes(); // true if table countries has a record with id GBR and it is active

use Coccoc\Validation\Factory;
use Coccoc\Validation\Rules\In;

$factory = new Factory();
$validation = $factory->validate($data, [
    'enabled' => [
        '

use Coccoc\Validation\Factory;

$factory = new Factory();
$validation = $factory->validate($data, [
    'enabled' => [
        '

$validation = $validator->validate([
    'photo' => $_FILES['photo']
], [
    'photo' => '

$validation = $validator->validate([
    'photo' => $_FILES['photo']
], [
    'photo' => '

use Coccoc\Validation\Factory;

$validation = (new Factory())->validate([
    'field' => 'value'
], [
    'field' => [
        '

use Coccoc\Validation\Factory;

$validation = (new Factory)->validate([
    'email' => '[email protected]'
], [
    'email' => 'email|unique:users,email',
]);

$validation->passes(); // true if table users does not contain the email

use Coccoc\Validation\Factory;

$validation = (new Factory)->validate([
    'email' => '[email protected]'
], [
    'email' => 'email|unique:users,email,10,id',
]);

$validation->passes(); // true if table users ignoring id 10, does not contain email

use Doctrine\DBAL\Query\QueryBuilder;
use Coccoc\Validation\Factory;
use Coccoc\Validation\Rules\Unique;

$factory    = new Factory;
$factory->addRule('unique', new Unique($dbalConn));

$validation = $factory->validate([
    'email' => '[email protected]'
], [
    'email' => $factory->rule('unique')->table('users')->column('email')->where(fn (QueryBuilder $qb) => $qb->andWhere('active = 1')),
]);

$validation->passes(); // true if table users does not contain an active email

$validation = (new Factory)->validate($_FILES, [
    'photos.*' => 'uploaded_file:0,2M,jpeg,png'
]);

// or

$validation = (new Factory)->validate($_FILES, [
    'photos.*' => 'uploaded_file|max:2M|mimes:jpeg,png'
]);

$validation = (new Factory)->validate($_FILES, [
    'images.*' => 'uploaded_file|max:2M|mimes:jpeg,png',
]);

// or

$validation = (new Factory)->validate($_FILES, [
    'images.profile' => 'uploaded_file|max:2M|mimes:jpeg,png',
    'images.cover' => 'uploaded_file|max:5M|mimes:jpeg,png',
]);

$validation = (new Factory)->validate($inputs, [
    'random_url' => 'url',          // value can be `any_scheme://...`
    'https_url' => 'url:http',      // value must be started with `https://`
    'http_url' => 'url:http,https', // value must be started with `http://` or `https://`
    'ftp_url' => 'url:ftp',         // value must be started with `ftp://`
    'custom_url' => 'url:custom',   // value must be started with `custom://`
]);

 declare(strict_types=1);

use Coccoc\Validation\Rule;

class UniqueRule extends Rule
{
    
    /**
     * @var string 
     */
    protected $message = ":attribute :value has been used";
    
    /**
     * @var array 
     */
    protected $fillableParams = ['table', 'column', 'except'];
    protected PDO $pdo;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    public function check($value): bool
    {
        // make sure aram(':value', $value);
        $stmt->execute();
        $data = $stmt->fetch(PDO::FETCH_ASSOC);

        // true for valid, false for invalid
        return intval($data['count']) === 0;
    }
}

use Coccoc\Validation\Factory;

$factory = new Factory();
$factory->addRule('unique', new UniqueRule($pdo));

$validation = $factory->validate($_POST, [
    'email' => 'email|unique:users,email,[email protected]'
]);

$params['table'] = 'users';
$params['column'] = 'email';
$params['except'] = '[email protected]';

$validation = $factory->validate($_POST, [
    'email' => [
    	'



class UniqueRule extends Rule
{
    public function table(string $table): self
    {
        $this->params['table'] = $table;
        
        return $this;
    }

    public function column(string $column): self
    {
        $this->params['column'] = $column;
        
        return $this;
    }

    public function except(string $value): self
    {
        $this->params['except'] = $value;
        
        return $this;
    }
}

$validation = $factory->validate($_POST, [
    'email' => [
    	't('[email protected]')
    ]
]);


use Coccoc\Validation\Rule;

class YourCustomRule extends Rule
{
    
    /**
     * @var bool 
     */
    protected $implicit = true;
}



use Coccoc\Validation\Rule;
use Coccoc\Validation\Rules\Contracts\ModifyValue;

class YourCustomRule extends Rule implements ModifyValue
{
    public function modifyValue($value)
    {
        // Do something with $value

        return $value;
    }
}



use Coccoc\Validation\Rule;
use Coccoc\Validation\Rules\Contracts\BeforeValidate;

class YourCustomRule extends Rule implements BeforeValidate
{
    public function beforeValidate(): void
    {
        $attribute = $this->getAttribute();
        $validation = $this->validation;

        // Do something with $attribute and $validation
        // For example change attribute value
        $validation->setValue($attribute->getKey(), "your custom value");
    }
}