PHP code example of ianaleck / guard

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

    

ianaleck / guard example snippets


use VGuard\VGuard;

$v = new VGuard;

$v->validate([
    'name'  => ['john', 'ion passed, woopie!';
} else {
    echo '<pre>', var_dump($v->errors()->all()), '</pre>';
}

$v->addRuleMessage('isbanana', 'The {field} field expects "mango", found "{value}" instead.');

$v->addRule('isbanana', function($value, $input, $args) {
    return $value === 'banana';
});

$v->validate([
    'fruit' => ['apple', 'isbanana']
]);

$v->addRuleMessage('

$v->addRuleMessages([
    'eld} needs to be an integer, but I found {value}.',
]);

$v->addFieldMessage('username', '

$v->addFieldMessages([
    'username' => [
        ' your age.',
        'int'      => 'Your age needs to be an integer.',
    ]
]);

$v->validate([
    'username_box|Username' => ['' => '

class MyValidator extends VGuard
{
    protected $db;

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

        // Add rule message for custom rule method.
        $this->addRuleMessage('uniqueUsername', 'That username is taken.');
    }

    // Custom rule method for checking a unique username in our database.
    // Just prepend custom rules with validate_
    public function validate_uniqueUsername($value, $input, $args)
    {
        $user = $this->db->prepare("
            SELECT count(*) as count
            FROM users
            WHERE username = :username
        ");

        $user->execute(['username' => $value]);

        if($user->fetchObject()->count) {
            return false; // Username exists, so return false.
        }

        return true;
    }
}

// A database connection.
$db = new PDO('mysql:host=127.0.0.1;dbname=website', 'root', 'root');

// Instantiate your custom class with dependencies.
$v = new MyValidator($db);

$v->validate([
    'username' => ['john', '

$v->validate([
    'username' => ['john', 'er)|max(100, number)']
]);

$twoDaysAgo = new DateTime('2 days ago');
$date = $twoDaysAgo->format('d M Y');

$v->validate([
    'date' => [$date, '