PHP code example of everest / validation

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

    

everest / validation example snippets


use Everest\Validation\Validation;

$int = Validation::integer('10'); // $int -> 10
$noint = Validation::integer('foo'); // Will throw \Everest\Validation\InvalidValidationException

use Everest\Validation\Validate;

$data = [
	'foo' => '10',
	'bar' => 'foo'
];

$data = Validate::lazy($data)
	->that('foo')->integer()->between(0, 20)
	->that('bar')->enum(['bar', 'foo'])->upperCase()
	->execute();

// $data -> ['foo' => 10, 'bar' => 'FOO']

use Everest\Validation\Validate;

$data = [
	'bar' => 'foo'
];

$data = Validate::lazy($data)
	->that('bar')->integer()->between(0, 20)
	->or()->string()->minLength(2)
	->execute();

// $data -> ['bar' => 'FOO']

use Everest\Validation\Validate;

$data = [
	'foo' => [
		['bar' => 1, 'name' => 'Some name'],
		['bar' => 2, 'name' => 'Some other name']
	]
];

$data = Validate::lazy($data)
	->that('foo.*.bar')->integer()->between(0, 20)
	->that('foo.*.name')->string()->upperCase()
	->execute();

// $data -> [
//   'foo' => [
//     ['bar' => 1, 'name' => 'SOME NAME'],
//     ['bar' => 2, 'name' => 'SOME OTHER NAME']
//   ]
// ]

use Everest\Validation\Validate;

$data = ['foo' => 10];

$result = Validate::lazy($data)
	->that('foo')->integer()
	->that('bar')->optional(/* no default */)->integer()
	->execute();

// $result -> ['foo' => 10]

$result = Validate::lazy($data)
	->that('foo')->integer()
	->that('bar')->optional(null)->integer()
	->execute();

// $result -> ['foo' => 10, 'bar' => null]



class CustomType extends \Everest\Validation\Types\Type {

	public static $errorName = 'invalid_custom_error';
	public static $errorMessage = '%s is not a valid custom type.';

	public function __invoke($value, $message = null, string $key = null, $customArg1 = null, $customArg2 = null)
	{
		if (/* Your invalid condition here */) {
			$message = sprintf(
				self::generateErrorMessage($message ?: self::$errorMessage),
				self::stringify($value)
			);

			throw new InvalidValidationException(self::$errorName, $message, $key, $value);
		}

		/**
		 * You may transform/cast the result before retuning it.
		 * In this case it is usefull to add a custom argument as 
		 * `$doCast` = false flag
		 */
		

		return $value;
	}
}




// Add as class. A singleton instance will be created when the type is requested the first time
\Everest\Validation\Validation::addType('custom_name', CustomType::CLASS);

// Add as instance. You can also supply a instance of your custom type. 
// E.g. when you need to do some configuration in `__construct()`
\Everest\Validation\Validation::addType('custom_name', new CustomType());