PHP code example of gajus / vlad

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

    

gajus / vlad example snippets


/**
 * @param Gajus\Vlad\Translator $translator
 */
$test = new \Gajus\Vlad\Test();

/**
 * Add an assertion to the test.
 *
 * @param string $selector_name
 * @return Gajus\Vlad\Assertion
 */
$assertion = $test->assert('user[first_name]');

/**
 * @param string $validator_name
 * @param array $validator_options
 * @param array $condition_options
 * @return Gajus\Vlad\Assertion
 */
$assertion->is('NotEmpty');
$assertion->is('String');
$assertion->is('LengthMin', ['length' => 5]);
$assertion->is('LengthMax', ['length' => 20]);

// In practise, assertion is declared using chaining:
$test
    ->assert('user[last_name]')
    ->is('NotEmpty')
    ->is('String')
    ->is('LengthMin', ['length' => 5])
    ->is('LengthMax', ['length' => 20]);

/**
 * @param array $source
 * @param string $selector_name
 * @return array Errors.
 */
$assessment = $test->assess($_POST);

if ($assessment) {
    // Iterate through error messages.
    foreach ($assessment as $error) {
        // [..]
    }
}

/**
 * @param string $selector_name
 * @param mixed $value
 * @return string Error.
 */
$error = $test->assertion('user[first_name]', $_POST);


namespace Foo\Bar;

class HexColor extends \Gajus\Vlad\Validator {
    static protected
        // Each option must be predefined with default value.
        $default_options = [
            'trim' => false
        ],
        $message = '{input.name} is not a hexadecimal number.';
    
    public function assess ($value) {
        $options = $this->getOptions();

        if ($options['trim']) {
            $value = ltrim($value, '#');
        }

        return ctype_xdigit($value) && (strlen($value) == 6 || strlen($value) == 3);
    }
}

$test = new \Gajus\Vlad\Test();
$test
    ->assert('foo_bar')
    ->is('Foo\Bar\HexColor');

$assessment = $test->assess(['foo_bar' => 'fff']);

$translator = new \Gajus\Vlad\Translator();
$translator->setInputName('foo[bar_tar_id]', 'Bar Tar');

$test = new \Gajus\Vlad\Test();
$test
    ->assert('foo_bar')
    ->is('NotEmpty');

$assessment = $test->assess([]);

$translator = new \Gajus\Vlad\Translator();
$translator->setValidatorMessage('NotEmpty', '{input.name} cannot be left empty.');

$test = new \Gajus\Vlad\Test($translator);
$test
    ->assert('foo_bar')
    ->is('NotEmpty');

$assessment = $test->assess([]);

$test = new \Gajus\Vlad\Test();
$test
    ->assert('foo_bar')
    ->is('NotEmpty', null, ['message' => 'You must provide Foo Bar value.']);

curl -s http://getcomposer.org/installer | php
php composer.phar