1. Go to this page and download the library: Download krak/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/ */
krak / validation example snippets
$validation = new Krak\Validation\Kernel();
$validator = $validation->make([
'name' => ' => 'RJ',
'age' => 17,
]);
if ($violations) { // you can also check $validator->failed()
print_r($violations->format()); // format into an array of error messages
}
use Krak\Validation;
/** enforces that a value equals a specific value */
function equalsStringValidator($match) {
return function($value, array $ctx = []) use ($match) {
if ($value == $match) {
return;
}
return Validation\violate('equals_string', [
'match' => $match
]);
};
}
$v = equalsStringValidator('foo');
$v('foo'); // returns null
$violation = $v('bar'); // return a Krak\Validation\Violation
$validation = new Krak\Validation\Kernel();
$validation->make([
'name' => 'e' => 100]);
// this will have thrown a ViolationException due to the age constraint
interface ValidationPackage
{
public function withValidation(Kernel $validation);
}
use Krak\Validation;
class AcmeValidationPackage implements Validation\ValidationPackage
{
public function withValidation(Validation\Kernel $v) {
$v->validators([
'integer' => 'intValidator', // name of intValidator func
'min' => MinValidator::class // name of MinValidator class
]);
$v->messages([
'integer' => 'The {{attribute}} is not a valid integer',
'min' => 'The {{attribute}} size must be greater than or equal to {{min}}',
]);
$v->aliases([
'int' => 'integer',
]);
}
}
use Krak\Validation;
// intValidator.php
function intValidator() {
return function($v) {
return !is_int($v) ? Validation\violate('integer') : null;
};
}
// MinValidator.php
class MinValidator implements Validation\Validator
{
private $min;
public function __construct($min) {
$this->min = $min;
}
public function validate($value, array $context = []) {
return $value < $min ? Validation\violate('min', ['min' => $this->min]) : null;
}
}
use Krak\Validation\Validators\Doctrine\AllExist;
use function Krak\Validation\Validators\{pipe, typeInteger, forAll};
pipe([forAll(typeInteger), new AllExist('users')])([1,2,3]);
use Krak\Validation\Validators\Doctrine\Entities;
use function Krak\Validation\Validators\{pipe, typeInteger, forAll};
pipe([forAll(typeInteger), new Entities('User')])([1,2,3]);