PHP code example of dsheiko / validate
1. Go to this page and download the library: Download dsheiko/validate 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/ */
dsheiko / validate example snippets
use \Dsheiko\Validate;
// Simple validation
$validate = new Validate();
$validate->IsString("hello")
->IsInt(42, ["min" => 0, "max" => 100])
->IsEmailAddress("[email protected] ");
if (!$validate->isValid()) {
foreach ($validate->getMessages() as $message) {
echo $message . "\n";
}
}
// Contract-based validation
Validate::contract([
"email" => ["[email protected] ", "IsEmailAddress"],
"age" => [25, ["IsInt" => ["min" => 18, "max" => 120]]],
]);
// Map validation
Validate::map($data, [
"username" => ["mandatory", "IsString" => ["minLength" => 3, "maxLength" => 20]],
"email" => ["mandatory", "IsEmailAddress"],
"age" => ["optional", "IsInt" => ["min" => 0, "max" => 150]],
]);
use \Dsheiko\Validate;
function login($email, $password)
{
// Validate preconditions using contract
Validate::contract([
"email" => [$email, "IsEmailAddress"],
"password" => [$password, ["IsString" => ["minLength" => 6, "maxLength" => 32, "notEmpty" => true]]],
]);
// Perform login logic...
// Validate postconditions if needed
Validate::contract([
"session_id" => [$sessionId, "IsUuid"],
]);
}
use \Dsheiko\Validate;
$formData = [
"username" => "john_doe",
"email" => "[email protected] ",
"password" => "secure_password",
"age" => 28,
"newsletter" => true,
];
Validate::map($formData, [
"username" => ["mandatory", "IsString" => ["minLength" => 3, "maxLength" => 50]],
"email" => ["mandatory", "IsEmailAddress"],
"password" => ["mandatory", ["IsString" => ["minLength" => 8, "maxLength" => 128, "notEmpty" => true]]],
"age" => ["optional", "IsInt" => ["min" => 0, "max" => 150]],
"newsletter" => ["optional", "IsBool"],
"phone" => ["optional", "IsString"], // Not in data, optional - OK
]);
use \Dsheiko\Validate;
$validate = new Validate();
$validate->IsString("[email protected] ")
->IsEmailAddress("[email protected] ")
->IsString("password123")
->IsInt(25, ["min" => 18, "max" => 120]);
if (!$validate->isValid()) {
// Handle validation errors
$messages = $validate->getMessages();
}