PHP code example of jeffersoncechinel / attribute-validator
1. Go to this page and download the library: Download jeffersoncechinel/attribute-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/ */
jeffersoncechinel / attribute-validator example snippets
C\Validator\Rules\Email;
use JC\Validator\Rules\Length;
use JC\Validator\Rules\NotNull;
use JC\Validator\Rules\Number;
use JC\Validator\Rules\Datetime;
use JC\Validator\Rules\UUID;
use JC\Validator\Rules\Range;
use JC\Validator\Validator;
class Example
{
#[NotNull]
public string|null $firstname = null;
#[NotNull]
#[Length(min: 0, max: 255)]
public string|null $lastname = null;
#[Email]
public string|null $email = null;
#[Range(min: 10, max: 20)]
public string|int|float $age;
#[Number(label: 'Price', errorMessage: '{label} is invalid.')]
public mixed $price;
#[Datetime(format: 'Y-m-d\TH:i:s.v\Z')]
public ?string $bornAt = null;
#[Datetime(format: 'Y-m-d')]
public ?string $createdAt = null;
#[Datetime(format: 'H:i')]
public ?string $time = null;
#[UUID]
public ?string $uuidv4 = null;
#[Number(positiveOnly: true)]
public ?string $positiveNumber = null;
#[Number(negativeOnly: true)]
public ?string $negativeNumber = null;
}
$example = new Example();
$example->firstname = null;
$example->lastname = "Smith";
$example->email = "john@invalidaemail";
$example->price = "$10.50";
$example->age = 5;
$example->bornAt = "2020-01-01T00:00:00.000Z";
$example->createdAt = "2020-01-01";
$example->time = "23:30";
$example->uuidv4 = "123e4567-e89b-12d3-a456-426614174000";
$example->positiveNumber = 10;
$example->negativeNumber = -10;
$validator = new Validator(
errorType: 'aggregatable'
);
$result = $validator->validate($example);
if ($result->hasErrors()) {
print_r($result->getErrors());
}