1. Go to this page and download the library: Download torugo/property-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/ */
torugo / property-validator example snippets
class SignInDto
{
#[IsRequired()]
#[MaxLenth(100)]
#[IsEmail()]
#[ToLowerCase()]
public $email = "";
#[IsRequired()]
#[IsString()]
#[Length(8, 100)]
public $password = "";
#[IsOptional()]
#[IsBoolean()]
public $keepConnected = false;
public function validate()
{
PropertyAttributes::validate($this);
}
}
use Torugo\PropertyValidator\PropertyValidator;
$signInDto = new SignInDto;
$signInDto->email = "[email protected]";
$signInDto->password = "MySuperStrongPassword!";
$signInDto->keepConnected = true;
// Using method inside the class
$signInDto->validate();
// or passing the instantiated class
PropertyValidator::validate($signInDto);
use Torugo\PropertyValidator\Exceptions\InvalidTypeException;
use Torugo\PropertyValidator\Exceptions\ValidationException;
try {
PropertyValidator::validate($signInDto);
} catch (ValidationException $ex) {
// Handle the error
} catch (InvalidTypeException $ex) {
// Handle the error
} catch (\Throwable $th) {
// Handle the error
}
class SignInDto
{
#[IsRequired("Email is 0 characters")]
#[IsEmail(errorMessage: "Invalid email")] // named argument
#[ToLowerCase()]
public $email = "";
//...
}
use Torugo\PropertyValidator\Attributes\Common\IsEqualTo;
#[IsEqualTo("A")]
public string $status = "A"; // valid
#[IsEqualTo("A")]
public string $status = "B"; // invalid
#[IsEqualTo(512)]
public $var = 512; // valid
#[IsEqualTo(512)]
public $var = 1024; // invalid
use Torugo\PropertyValidator\Attributes\Common\IsOptional;
#[IsOptional()]
public mixed $prop = null; // valid
#[IsOptional()]
public ?string $prop = ""; // valid, string can be emtpy
#[IsOptional()]
public ?array $prop = []; // valid, array can be empty
#[IsOptional()]
public string $prop = null; // invalid, should be setted as ?string
use Torugo\PropertyValidator\Attributes\Common\IsRequired;
#[IsRequired("Password cannot be empty")]
public string $password = ""; // invalid
#[IsRequired("My prop cannot be empty")]
public array $prop = []; // invalid
#[IsRequired("Prop can't be empty or null")]
public mixed $prop = null; // invalid
use Torugo\PropertyValidator\Attributes\Common\SameAs;
// VALID
public $password = "MySuperStrongPassword!";
#[SameAs("password")]
public $repeat = "MySuperStrongPassword!";
//INVALID - Property name is case sensitive
public $password = "MySuperStrongPassword!";
#[SameAs("Password")]
public $repeat = "MySuperStrongPassword!";
// INVALID - Values must have the same type
public $number1 = 512;
#[SameAs("number1")]
public $number2 = "512";
// INVALID - If target property does not exist
public $propA = "My Prop";
#[SameAs("propC")]
public $propB = "My Prop";
use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsArray;
use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsBoolean;
#[IsBoolean()]
public mixed $prop = true;
#[IsBoolean()]
public mixed $prop = "no"; // Is evaluated as false, but not converted
#[IsBoolean(true)]
public mixed $prop = "yes"; // Will convert to true
use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsDateTime;
#[IsDateTime()]
public string $dt = "2024-06-26 13:56:24"; // valid
#[IsDateTime("M d Y", true)]
public mixed $prop = "Jun 26 2024"; // valid, will be converted to \DateTime object
#[IsDateTime("m-d-Y")]
public mixed $prop = "2017-08-01"; // Throws ValidationException due to icompatible date/time format
#[IsDateTime("m-d-Y", true)]
public string $prop = "2017-08-01'; // Throws InvalidTypeException, property type should be 'mixed"
use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsEnum;
#[IsEnum(DeskOS::class)]
public string $desktopOS = "L"; // valid
#[IsFloat(Database:class)]
public int $database = 1; // valid
#[IsFloat(Database:class)]
public int $database = 3; // Invalid, not exists
#[IsFloat(MobileOS:class)]
public mixed $num = "Android"; // Invalid, not backed enum
use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsFloat;
#[IsFloat()]
public float $num = 3.1415; // valid
#[IsFloat()]
public float $num = 124; // valid
#[IsFloat()]
public mixed $num = "9.99"; // Invalid
use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsFloat;
#[IsInt()]
public int $num = 2048; // valid
#[IsInt()]
public mixed $num = 9.99; // invalid
#[IsInt()]
public mixed $num = "512"; // Invalid
use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsNumeric;
#[IsNumeric()]
public $num = 2048; // valid
#[IsNumeric()]
public mixed $num = 9.99; // valid
#[IsNumeric()]
public mixed $num = "512.256.128,64"; // valid
#[IsNumeric()]
public mixed $num = "USD 9.99" ; // Invalid
#[IsNumeric()]
public int $num = 1983; // Invalid, property must be declared as mixed
use Torugo\PropertyValidator\Attributes\Validators\TypeCheckers\IsString;
#[IsString()]
public string $prop = "I'll be back"; // valid
#[IsString()]
public mixed $prop = "R$ 3.547,61"; // valid
#[IsString()]
public $prop = ["A", "B", "C"]; // invalid
#[IsString()]
public $prop = 898; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayContains;
#[ArrayContains("banana")]
public $arr = ["apple", "banana", "grapes", "orange"];
// Valid
#[ArrayContains("BANANA")]
public $arr = ["apple", "banana", "grapes", "orange"];
// Invalid, string search is case sensitive
#[ArrayContains(20)]
public $arr = [10, 20, 30, 40];
// Valid
#[ArrayContains("20")]
public $arr = [10, 20, 30, 40];
// Invalid, strict type enabled
#[ArrayContains(20, false)]
public $arr = ["10", "20", "30", "40"];
// Valid, strict type disabled
#[ArrayContains("Appleseed")]
public $arr = ["firstName" => "Jhon", "lasName" => "Appleseed"];
// Valid
#[ArrayContains(["30", "40"])]
public $arr = ["10", "20", ["30", "40"]];
// Valid
use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayMaxSize;
// Valid
#[ArrayMaxSize(4)]
public $arr = ["apple", "banana", "grapes", "orange"];
// Valid
#[ArrayMaxSize(2)]
public $arr = ["firstName" => "Bilbo", "lastName" => "Baggins"];
// Invalid, throws ValidationException when overflows
#[ArrayMaxSize(4)]
public $arr = ["apple", "banana", "grapes", "orange", "pear"];
use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayMinSize;
// Valid
#[ArrayMinSize(2)]
public $arr = ["apple", "banana", "grapes", "orange"];
// Valid
#[ArrayMinSize(2)]
public $arr = ["firstName" => "Bilbo", "lastName" => "Baggins"];
// Invalid, throws ValidationException when the number of elements is lesser
#[ArrayMinSize(3)]
public $arr = ["apple", "banana"];
use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayNotContains;
use Torugo\PropertyValidator\Attributes\Validators\Arrays\ArrayNotContains;
// Valid
#[ArrayNotContains("pineapple")]
public $arr = ["apple", "banana", "grapes", "orange"];
// Invalid
#[ArrayNotContains("orange")]
public $arr = ["apple", "banana", "grapes", "orange"];
// Invalid
#[ArrayNotContains(30)]
public $arr = [10, 20, 30, 40];
// Valid, strict type enabled
#[ArrayNotContains("30")]
public $arr = [10, 20, 30, 40];
// Invalid, strict type disabled
#[ArrayNotContains(30, false)]
public $arr = ["10", "20", "30", "40"];
// Valid
#[ArrayNotContains("Luke")]
public $arr = ["firstName" => "Han", "lasName" => "Solo"];
// Invalid
#[ArrayNotContains(["30", "40"])]
public $arr = ["10", "20", ["30", "40"]];
use Torugo\PropertyValidator\Attributes\Validators\DateTime\MaxDateTime;
#[MaxDateTime(new DateTime("now + 10 days"))]
public DateTime $date = new DateTime("now");
// Here you can receive a date/time string
#[IsDateTime("Y-m-d H:i:s", true)] // set 'toDateTime' to true
#[MaxDateTime(new DateTime("now + 10 days"))]
public mixed $dtString = "2024-13-03 12:30:45";
use Torugo\PropertyValidator\Attributes\Validators\DateTime\MinDateTime;
#[MinDateTime(new DateTime("now"))]
public DateTime $date = new DateTime("now +1 day");
// Here you can receive a date/time string
#[IsDateTime("Y-m-d H:i:s", true)] // set 'toDateTime' to true
#[MinDateTime(new DateTime("2024-13-03 12:30:45"))]
public mixed $dtString = "2024-13-03 12:30:46";
use Torugo\PropertyValidator\Attributes\Validators\Numbers\IsDibisibleBy;
#[IsDivisibleBy(2)]
public $num1 = 10; // valid
#[IsDivisibleBy(2.5)]
public $num1 = 7.5; // valid
#[IsDivisibleBy(3)]
public $num1 = 11; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Numbers\IsNegative;
#[IsNegative()]
public $num1 = -13; // valid
#[IsNegative()]
public $num1 = -9.99; // valid
#[IsNegative()]
public $num1 = 0; // invalid
#[IsNegative()]
public $num1 = 12; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Numbers\IsPositive;
#[IsPositive()]
public $num1 = 512; // valid
#[IsPositive()]
public $num1 = 3.1415; // valid
#[IsPositive()]
public $num1 = 0; // invalid
#[IsPositive()]
public $num1 = -19.99; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Numbers\Max;
#[Max(1024)]
public $num1 = 512; // valid
#[Max(999.99)]
public $num1 = 999.99; // valid
#[Max(-10)]
public $num1 = -11; // valid
#[Max(10)]
public $num1 = 11; // invalid
#[Max(0)]
public $num1 = 1; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Numbers\Min;
#[Min(256)]
public $num1 = 256; // valid
#[Min(9.99)]
public $num1 = 12.99; // valid
#[Min(-5)]
public $num1 = -4; // valid
#[Min(10)]
public $num1 = 9; // invalid
#[Min(1)]
public $num1 = 0; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Numbers\Range;
#[Range(0, 16)]
public $number = 9; // valid
#[Range(1, 9.99)]
public $number = "8.72"; // valid
#[Range(-10, 0)]
public $number = -4; // valid
#[Range(20, 0)] // will be swapped
public $number = 19; // valid
#[Range(0, 100)]
public $number = 101; // invalid
#[Range(1, 9.99)]
public $number = 10; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Strings\Contains;
#[Contains("Approved")]
public string $prop = "Approved"; // valid
#[Contains("Approved")]
public mixed $prop = "Refused"; // invalid
#[Contains("Approved", false)] // case sensitiveness disabled
public $prop = "APPROVED"; // valid
#[Contains("Approved")] // case sensitiveness enalbed
public $prop = "APPROVED"; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsAlpha;
#[IsAlpha()]
public string $prop = "UZoljlNxrCYJUpDgmDmCA"; // valid
#[IsAlpha(true)] // unicode enabled
public string $prop = "XOÄfsàugKjLcpGEJÄwbvàX"; // valid
#[IsAlpha()]
public mixed $prop = "No spaces allowed"; // invalid
#[IsAlpha()]
public mixed $prop = "Wdj6Ab0pkhkS3HqUwTza"; // numbers are invalid
#[IsAlpha(true)]
public mixed $prop = "[email protected]"; // invalid, symbols or ponctuation
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsAlphanumeric;
#[IsAlphanumeric()]
public string $prop = "mSfPq4Tc9ipPgX5487NG"; // valid
#[IsAlphanumeric(true)] // unicode enabled
public string $prop = "çeY4â2e4SÇ8ÂdiÀÏKTLÊ"; // valid
#[IsAlphanumeric()]
public mixed $prop = "No spaces allowed"; // invalid
#[IsAlphanumeric(true)]
public mixed $prop = "[email protected]"; // invalid, symbols or ponctuation
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsBase64;
#[IsBase64()]
public string $b64 = "7d+n67ptfj/J+Q+O0cQ1+w=="; // valid
#[IsBase64()]
public string $b64 = "7d-n67ptfj_J-Q-O0cQ1-w"; // valid, url safe
#[IsBase64()]
public string $b64 = "7d+n67ptfj/J+Q+O0cQ1+w"; // valid, '=' right padding
#[IsBase64()]
public mixed $b64 = "FKgLuXN\qsxYnEgtyzKyxQ=="; // invalid
#[IsBase64()]
public mixed $b64 = "=HAMYja0H18A"; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsCnpj;
#[IsCnpj()]
public $cnpj = '60391682000132';
// Valid
#[IsCnpj()]
public $cnpj = '99.453.669/0001-04';
// Valid, this is the default format
#[IsCnpj()]
public $cnpj = '99 453 669 / 0001 (04)';
// Valid, it removes non numerical characters
#[IsCnpj()]
public $cnpj = '99.453.669/0001-05';
// Invalid verification digit
#[IsCnpj()]
public $cnpj = '9953669000105';
// Invalid length
#[IsCnpj()]
public $cnpj = '999.453.669/0001-04';
// Invalid length
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsCpf;
#[IsCpf()]
public $cpf = '88479747048';
// Valid
#[IsCpf()]
public $cpf = '532.625.750-54';
// Valid, this is the default format
#[IsCpf()]
public $cpf = '532 625 750 (54)';
// Valid, it removes non numerical characters
#[IsCpf()]
public $cpf = '532.625.750-55';
// Invalid verification digit
#[IsCpf()]
public $cpf = '53.625.750-54';
// Invalid length
#[IsCpf()]
public $cpf = '532.625.750-541';
// Invalid length
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsEmail;
#[IsEmail()]
public string $email = "[email protected]"; // valid
#[IsEmail()]
public string $email = "[email protected]"; // valid
#[IsEmail()]
public mixed $email = "hans@m端ller.com"; // invalid
#[IsEmail()]
public mixed $email = "wrong()[],:;<>@@gmail.com"; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsIP;
#[IsIP(4)] // Only IPv4
public $ip1 = "127.0.0.1";
#[IsIP(6)] // Only IPv6
public $ip2 = "fe80::a6db:30ff:fe98:e946";
#[IsIP()] // Both
public $ip3 = "185.85.0.29";
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsSemVer;
#[IsSemVer()]
public $version = "1.0.0"; // valid
#[IsSemVer()]
public $version = "1.0.0-beta.1"; // valid
#[IsSemVer()]
public $version = "1.0.0+20"; // valid
#[IsSemVer()]
public $version = "alpha.beta"; // invalid
#[IsSemVer()]
public $version = "1.0.0-alpha_beta"; // invalid
#[IsSemVer()]
public $version = "1.01.1"; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsTUID;
#[IsTUID()]
public $short = "UU5IM7L-TS0SQK0Y3101"; // valid
#[IsTUID()]
public $medium = "V6ZS389O-SMXM-TM0SQK0Y3116"; // valid
#[IsTUID()]
public $long = "VPD1QAMA-XBFK-AVF7SSP67-TL0SQK0Y311B"; // valid
#[IsTUID()]
public $uuid = "E8ABFEBA-C1FE-4491-8DFA-609C5EEF825B"; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Strings\IsURL;
new UrlOptions(
: false, // expects the protocol to be present in the url
rue,
alse,
allowFragments: true,
allowQueryComponents: true,
allowAuth: true,
allowNumericTld: false,
allowWildcard: false,
validateLength: true,
);
///
/// VALID
///
#[IsUrl()]
public $url = 'foobar.com';
#[IsUrl()]
public $url = 'www.foobar.com';
#[IsUrl()]
public $url = 'http://www.foobar.com/';
#[IsUrl()]
public $url = 'http://127.0.0.1/';
#[IsUrl()]
public $url = 'http://10.0.0.0/';
#[IsUrl()]
public $url = 'http://189.123.14.13/';
#[IsUrl()]
public $url = 'http://duckduckgo.com/?q=%2F';
///
/// INVALID
///
#[IsUrl()]
public $url = 'http://www.foobar.com:0/';
#[IsUrl()]
public $url = 'http://www.foobar.com:70000/';
#[IsUrl()]
public $url = 'http://www.foobar.com:99999/';
#[IsUrl()]
public $url = 'http://www.-foobar.com/';
#[IsUrl()]
public $url = 'http://www.foobar-.com/';
use Torugo\PropertyValidator\Attributes\Validators\Strings\Length;
#[Length(1, 60)]
public $text = "They may take our lives, but they'll never take our freedom!"; // valid
#[Length(8, 64)]
public $password = "9a2f534"; // invalid
use Torugo\PropertyValidator\Attributes\Validators\Strings\Matches;
#[Matches("/^#(?:[0-9a-fA-F]{3}){1,2}$/")]
public $color = "#0ABAB5";
#[Matches("\d{5}([ \-]\d{4})?")]
public mixed $zip = "98101";
#[Matches("/<\/?[\w\s]*>|<.+[\W]>/")]
public $tag = "<h1>Torugo</h2>";
use Torugo\PropertyValidator\Attributes\Validators\Strings\MaxLength;
#[MaxLength(60)]
public $text = "They may take our lives, but they'll never take our freedom!"; // valid
#[MaxLength(64)]
public $password = "9a2f534"; // invalid
// In order to accept empty strings you
// will have to use IsOptional attribute
#[IsOptional()]
#[MaxLength(10)]
public $prop1 = ""; // valid
#[MaxLength(10)]
public $prop2 = ""; // invalid
#[MinLength(12)]
public $text = "Nunc placerat a turpis vitae."; // valid
#[MinLength(10)]
public $prop = "My Prop"; // invalid, lesser than min arg
#[MinLength(0)]
public $prop = ""; // valid, makes no sense, but is valid. Why not use only 'IsString()'?
use Torugo\PropertyValidator\Attributes\Validators\Strings\NotContains;
#[NotContains("Break")]
public string $prop = "Break a leg"; // throws ValidationException
#[NotContains("CUT")]
public mixed $prop = "To cut corners"; // not throws, case sensitiveness enabled
#[NotContains("BULLET", false)] // Case sensitiveness enabled
public $prop = "Bite the bullet"; // throws ValidationException
use Torugo\PropertyValidator\Attributes\Handlers\Common\CopyFrom;
public $target = "My String";
#[CopyFrom("target")]
public $copy; // "My String"
use Torugo\PropertyValidator\Attributes\Handlers\Convertions\Explode;
use Torugo\PropertyValidator\Attributes\Handlers\Convertions\Implode;
use Torugo\PropertyValidator\Attributes\Handlers\Convertions\Join;
#[Join()]
public $alpha = ["A", "B", "C", ["D", "E", "F"]];
// "ABCDEF" -> Is recursively
// Using the native PHP implode function the result would be "ABCArray"
#[Join(".")]
public $ip = ["123", "456", "789", "001"];
// "123.456.789.001"
#[Implode(" ")]
public $name = ["firstName" => "Conceição", "lastName" => "Evaristo"];
// "Conceição Evaristo"
#[Join(" - ", true, ": ")]
public $form = ["firstName" => "José", "lastName" => "Alencar"];
// "firstName: José - lastName: Alencar"
use Torugo\PropertyValidator\Attributes\Handlers\Convertions\Split;
#[Split(" ")]
public mixed $lipsum = "Ut rutrum mauris eget pulvinar";
// ["Ut", "rutrum", "mauris", "eget", "pulvinar"]
#[Split(".")]
public mixed $ip = "123.456.789.001";
// ["123", "456", "789", "001"]
#[Split("-", 4)]
public mixed $serial = "lvnr-MHba-hb6G-Mezq-8I55-eyZv";
// ["lvnr", "MHba", "hb6G", "Mezq-8I55-eyZv"]
#[Split("-", -2)]
public mixed $str = "lvnr-MHba-hb6G-Mezq-8I55-eyZv";
// ["lvnr", "MHba", "hb6G", "Mezq"]
#[Split("-", -2)]
public string $str = "lvnr-MHba-hb6G-Mezq-8I55-eyZv";
// throws InvalidTypeException, property must be mixed
use Torugo\PropertyValidator\Attributes\Handlers\Strings\Append;
#[Append(".")]
public $phrase = "My phrase"; // "My phrase."
#[Append("!")]
#[Append("?")]
public $str = "My String"; // "My String!?"
php
#[PasswordHash()]
public mixed $pass1 = "5up3rStr0ngP4ssw0rd!";
// $2y$10$SliJ/ky9gIr0XyAJmnjtM.tG94h6wXUy0BSeMsuMMxXs9aHjWW5HO
#[PasswordHash(PASSWORD_ARGON2I)]
public mixed $pass2 = "tKxSYVBH+Te2rb5nUWN87&";
// $argon2i$v=19$m=65536,t=4,p=1$NWNzR3JwSmlyYktQVTBELw$uCfkmLa7EJTzNzKySOxjGeN44RyQmJn8hFyNBF1nW7A
#[PasswordHash(PASSWORD_BCRYPT, ["cost" => 10])]
public mixed $pass3 = "LzM#KFSqk9Uwb7TQsYA3JW";
// $2y$10$qsByI6OVsNgPS6TdKUs.Ve9hYml27ZRVdQV2WB1iZjhWSDhSbpVZS
php
#[SetValueWhenNull("")]
public ?string $str = null; // Will be setted to `""`
#[SetValueWhenNull(0)]
public ?int $int = null; // Will be setted to `0`
#[SetValueWhenNull([])]
public ?array $arr = null; // Will be setted to `[]`
php
use Attribute;
use Torugo\PropertyValidator\Abstract\Validator;
#[Attribute(Attribute::TARGET_PROPERTY)]
class MyValidator extends Validator
{
public function __construct(
private $arg1,
private $arg2,
private ?string $errorMessage = null
) {
parent::__construct($errorMessage);
}
public function validation(mixed $value): void
{
// Validate the data
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.