PHP code example of somnambulist / validation

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

    

somnambulist / validation example snippets




omnambulist\Components\Validation\Factory;

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



omnambulist\Components\Validation\Factory;

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

use Somnambulist\Components\Validation\Factory;

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

use Somnambulist\Components\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 Somnambulist\Components\Validation\Factory;
use Somnambulist\Components\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

use Somnambulist\Components\Validation\Factory;

$validation = $factory->validate([
    'filters' => ['foo' => 'bar', 'baz' => 'example']
], [
    'filters' => 'array|array_must_have_keys:foo,bar,baz',
]);

$validation->passes(); // true if filters has all the keys in array_must_have_keys

use Somnambulist\Components\Validation\Factory;

$validation = $factory->validate([
    'filters' => ['foo' => 'bar', 'baz' => 'example']
], [
    'filters' => 'array|array_must_have_keys:foo,bar,baz',
    'filters.foo' => 'string|between:1,50',
    'filters.bar' => 'numeric|min:1',
    'filters.baz' => 'uuid',
]);

$validation = $factory->validate([
    'filters' => ['foo' => 'bar', 'baz' => 'example']
], [
    'filters' => 'array',
    'filters.foo' => '

use Somnambulist\Components\Validation\Factory;

$validation = $factory->validate([
    'filters' => ['foo' => 'bar', 'baz' => 'example']
], [
    'filters' => 'array|array_can_only_have_keys:foo,bar',
]);

$validation->passes(); // true if filters only has the keys in array_can_only_have_keys

$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 Somnambulist\Components\Validation\Factory;

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

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

use Somnambulist\Components\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 Somnambulist\Components\Validation\Factory;
use Somnambulist\Components\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 Somnambulist\Components\Validation\Factory;
use Somnambulist\Components\Validation\Rules\In;

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

use Somnambulist\Components\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 Somnambulist\Components\Validation\Factory;

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

use Somnambulist\Components\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 Somnambulist\Components\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 Somnambulist\Components\Validation\Factory;
use Somnambulist\Components\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://`
]);

[
    'filters' => 'sometimes|array',
]

[
    'skills'              => 'array',
    'skills.*.id'         => '

[
    'skills' => [
        [
            'id' => 3,
            'percentage' => 50,
        ],
        [
            'id' => 17,
            'percentage' => 50,
        ],
    ]
]

[
    '*.id'         => 'equired|numeric'
]

[
    [
        'id' => 3,
        'percentage' => 50,
    ],
    [
        'id' => 17,
        'percentage' => 50,
    ],
]

[
    'name' => 'foo bar',
    [
        'id' => 3,
        'percentage' => 50,
    ],
    [
        'id' => 17,
        'percentage' => 50,
    ],
]

[
    'skills.*.id'         => 'sometimes|numeric',
    'skills.*.percentage' => '

[
    '*.id'         => 'sometimes|numeric',
    '*.percentage' => '

use Somnambulist\Components\Validation\Factory;

$factory = new Factory();
$factory->registerLanguageMessages('de');

use Somnambulist\Components\Validation\Factory;

$factory = new Factory();
$factory->registerLanguageMessages('en', '/path/to/project/i18n/en_US.php');

use Somnambulist\Components\Validation\Factory;

$factory = new Factory();
$factory->registerLanguageMessages('en', '/path/to/project/i18n/en_US.php');
$factory->registerLanguageMessages('es', '/path/to/project/i18n/es.php');
$factory->registerLanguageMessages('de', '/path/to/project/i18n/de.php');

use Somnambulist\Components\Validation\Factory;

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

use Somnambulist\Components\Validation\Factory;

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

use Somnambulist\Components\Validation\Factory;

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

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

use Somnambulist\Components\Validation\Factory;

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

use Somnambulist\Components\Validation\Factory;

$factory = new Factory();
$factory->messages()->replace('en', 'password:between', 'Your password must be between :min and :max characters and only [! $ % + .] as special characters.');
$factory->messages()->replace('en', 'password:regex', 'Your password must be between :between.min and :between.max characters and only [! $ % + .] as special characters.');

use Somnambulist\Components\Validation\Factory;

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

use Somnambulist\Components\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();

 declare(strict_types=1);

use Somnambulist\Components\Validation\Rule;

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

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

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

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

use Somnambulist\Components\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 Somnambulist\Components\Validation\Rule;

class YourCustomRule extends Rule
{
    protected bool $implicit = true;
}



use Somnambulist\Components\Validation\Rule;
use Somnambulist\Components\Validation\Rules\Contracts\ModifyValue;

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

        return $value;
    }
}



use Somnambulist\Components\Validation\Rule;
use Somnambulist\Components\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");
    }
}