PHP code example of azolee / validator

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

    

azolee / validator example snippets


use Azolee\Validator\Validator;

$validationRules = [
    'user.name' => 'string',
    'user.age' => 'numeric',
    'user.email' => ['email', 'not_null'],
    'user.website' => ['url'],
    'user.password' => ['password:ulds', 'min:8'],
    'user.password_confirmation' => ['same:user.password'],
    'user.is_active' => ['boolean', 'not_null'],
    'address' => 'array',
    'address.city' => 'string',
    'address.street' => ['string', 'different:address.city', 'different:address.street2', 'different:address.no'],
    'address.street2' => 'not_null',
    'address.no' => 'string',
    'images.*.url' => 'string',
    'images.*.role' => ['string', 'in:profile_photo,album_photo'],
];

$dataToValidate = [
    'user' => [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'password' => 'SecretPasswd#1',
        'password_confirmation' => 'secret',
        'website' => 'https://github.com',
        'age' => 30,
        'is_active' => true,
    ],
    'address' => [
        'city' => 'New York',
        'street' => 'First Avenue',
        'street2' => '',
        'no' => '52A',
    ],
    'images' => [
        [
            'url' => 'image1.jpg'
            'role' => 'profile_photo',
        ],
        [
            'url' => 'image2.jpg'
            'role' => 'album_photo',
            'description' => 'This is a photo of me.',
        ],
    ],
];

$result = Validator::make($validationRules, $dataToValidate);

if ($result->isFailed()) {
    echo "Validation failed!";
    print_r($result->getFailedRules());
} else {
    echo "Validation passed!";
}

$validationRules = [
    'user.name' => [
        function ($data) {
            return $data !== 'John Doe';
        },
        'string',
    ],
];

$dataToValidate = [
    'user' => [
        'name' => 'John Smith'
    ],
];

$result = Validator::make($validationRules, $dataToValidate);

if ($result->isFailed()) {
    echo "Validation failed!";
    print_r($result->getFailedRules());
} else {
    echo "Validation passed!";
}

use Azolee\Validator\Exceptions\InvalidValidationRule;
use Azolee\Validator\Exceptions\ValidationException;

try {
    $validationRules = [
        'name' => 123, // Invalid rule
    ];
    $dataToValidate = [
        'name' => 'John Doe',
    ];

    Validator::config(['silent' => false])->make($validationRules, $dataToValidate);
} catch (InvalidValidationRule $e) {
    echo "Caught an InvalidValidationRule exception: " . $e->getMessage();
} catch (ValidationException $e) {
    echo "Caught a ValidationException: " . $e->getMessage();
}