Download the PHP package torugo/property-validator without Composer

On this page you can find all versions of the php package torugo/property-validator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package property-validator

Property Validator

Validators and Handlers for class properties.
Commonly used to create DTOs (Data Transfer Objects).

Inspired by class-validator for Typescript.

Table of Contents

Requirements

Instalation

On your terminal type:

Or add to your require list on composer.json file:

Usage

This library is based on the PHP Attributes resource.

Example

Validating the data

There are two ways to validate property values:

  1. by adding a method inside your class that calls PropertyValidator::validate like example above;
  2. Or by calling it from anywhere passing an instance of the class.

Example

Using the class SignInDto from usage example above.

Error Handling

Validators can throw:

InvalidTypeException:
Thrown when the property type is incorrect, or when the type of the received value is invalid.

ValidationException:
Thrown on validation errors, the value type is correct but, its content is invalid.

So you can wrap the validation in a try/catch block.

Examples

or

Custom error message

All VALIDATING ATTRIBUTES have an argument called $errorMessage, where you can define a custom error message. If not defined, the default error messages from each validator will be thrown.

Consult each validator's documentation to see the position of the argument, or use PHP's named arguments feature.

Example

Validators

Set of attributes that validate the properties of a class, do not change its value, only check whether the data respects a certain rule of each validator.

Validators can throw ValidationException and InvalidTypeException.

Common

IsEqualTo

Validates whether the value of a property exactly equals to a given value.

Examples


IsOptional

Defines a property as optional, so its value can be empty or null.

[!NOTE] By default, all properties of a class that use any of the attributes of this library are treated as NON NULLABLE, but their values can be empty.

Examples

[!IMPORTANT] When setting the type of a property other than "mixed", you must set the type to optional as well by placing a question mark a the beggining.
E.g. ?string, ?int, ?array, ...


IsRequired

Defines a property as required, so that the value cannot be null or empty.

By default, all properties of a class that use any of the attributes in this library are treated as NON NULLABLE, so using this attribute their values cannot be empty as well.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


SameAs

Validates whether the value of a property is strictly equal to another in the same class

Parameters

Parameter Type Description
target string Name of the property to be compared.
errorMessage string Custom error message.

Examples


Type Checkers

IsArray

Validates whether the value of a property is an array.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


IsBoolean

Validates wheter a property data is a valid boolean value.

Parameters

Parameter Type Description
convertToBoolean bool Converts accepted values to boolean. (Default: false)
errorMessage string Custom error message.

Examples

Accepted values:

Value Type Evaluate as
1 int TRUE
"1" string TRUE
"true" string TRUE
"t" string TRUE
"ok" string TRUE
"yes" string TRUE
"y" string TRUE
"sim" string TRUE
"s" string TRUE
0 int FALSE
"0" string FALSE
"false" string FALSE
"f" string FALSE
"no" string FALSE
"not" string FALSE
"n" string FALSE
"não" string FALSE
"nao" string FALSE

IsDateTime

Validates whether the property value is a valid date time string.

Parameters

Parameter Type Description
format string Valid PHP DateTime::format (Default: "Y-m-d H:i:s").
toDateTime bool Converts date time string to PHP DateTime object (Default: false)
errorMessage string Custom error message.

Examples


IsDouble

IsDouble is just an alias to IsFloat validator.


IsEnum

Validates if the property's value is a member of a given backed enum.

Parameters

Parameter Type Description
enum string The enum name.
errorMessage string Custom error message.

Examples

[!IMPORTANT] The ENUM used to validate the data must be BACKED.

Valid
String enum
Valid
Int enum
Invalid
Not backed enum
enum DeskOS: string
{
  case Linux = "L";
  case MacOS = "M";
  case Windows = "W";
}
enum Database: int 
{
  case MySql = 0;
  case Postgres = 1;
  case Mongo = 2;
}
enum MobileOS
{
  case Android;
  case iOS;
  case iPadOS;
}

IsFloat

Validates if a value's type is FLOAT.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


IsInt

Validates whether the value of a property is of type integer.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


IsInteger

IsInterger is just an alias to IsInt validator.


IsNumeric

Validates whether the value of a property is numeric. Only float, int or numeric string types are allowed.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples

[!IMPORTANT] This validator requires the property to be set to mixed


IsString

Validates whether the type of a value is string.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples

Arrays

ArrayContains

Validates whether an array contains a given value.

Parameters

Parameter Type Description
search mixed If string, the comparison is done in a case-sensitive manner.
strict bool The type of searched value should match. (Default: true).
errorMessage string Custom error message.

Examples

TODO:
Implements case insensitive string search.

ArrayMaxSize

Checks whether the number of elements in an array is less than or equal to a specified number.

Parameters

Parameter Type Description
max int Maximum accepted elements. Must be >= 1.
errorMessage string Custom error message.

Examples


ArrayMinSize

Checks whether the number of elements in an array is greater than or equal to a specified number.

Parameters

Parameter Type Description
min int Minimum accepted elements. Must be >= 1.
errorMessage string Custom error message.

Examples


ArrayKeyExists

Validates whether an array has one or more keys.

Parameters

Parameter Type Description
keys array Keys that must be present in the array.
caseSensitive bool The search for keys should or should not be case sensitive. (Default true)
errorMessage string Custom error message.

Examples


ArrayNotContains

Works in the opposite direction to ArrayContains.
Throws ValidationException when a certain value is found in an array.

Parameters

Parameter Type Description
search mixed If string, the comparison is done in a case-sensitive manner.
strict bool The type of searched value should match. (Default: true).
errorMessage string Custom error message.

Examples

TODO:
Implements case insensitive string search.


Date/Time

MaxDateTime

Validates whether a DateTime instance is greater than a defined limit.

Parameters

Parameter Type Description
max DateTime Maximum acceptable Date/Time.
errorMessage string Custom error message.

Examples

[!IMPORTANT] If you intend to validate date/time in strings, you must first use the IsDateTime attribute, and set the 'toDateTime' argument to true, in these cases it is mandatory to set the property type to mixed. See the examples below.


MinDateTime

Validates whether a DateTime instance is before than a defined minimum date/time.

Parameters

Parameter Type Description
min DateTime Minimum acceptable Date/Time.
errorMessage string Custom error message.

Examples

[!IMPORTANT] If you intend to validate date/time in strings, you must first use the IsDateTime attribute, and set the 'toDateTime' argument to true, in these cases it is mandatory to set the property type to mixed. See the examples below.


Numbers

IsDivisibleBy

Validates whether a number (int or float) is divisible by a given one.

Parameters

Parameter Type Description
divisor int or float The divisor number.
errorMessage string Custom error message.

Examples


IsNegative

Validates if property's value is negative (lesser than zero).

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


IsPositive

Validates if a number is positive (greater than zero).

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


Max

Validates whether a number (int or float) is less than or equal to a given number.

Parameters

Parameter Type Description
max int or float Maximum acceptable number.
errorMessage string Custom error message.

Examples


Min

Validates whether a number (int or float) is greater than or equal to a given number.

Parameters

Parameter Type Description
min int or float Minimum acceptable number.
errorMessage string Custom error message.

Examples


Range

Validates whether a number falls within a given inclusive range.

Parameters

Parameter Type Description
min int or float Minimum acceptable number.
max int or float Maximum acceptable number.
errorMessage string Custom error message.

Examples


Strings

[!IMPORTANT] All string validators in this section extend the IsString validator, so its use is unnecessary.

Contains

Validates whether a substring is contained in the property's value.

Parameters

Parameter Type Description
substring string The substring to search for in the property's value.
caseSensitive bool Case sensitiveness. (Default: true)
errorMessage string Custom error message.

Examples


IsAlpha

Validates if a string have only alphabetical characters.

Parameters

Parameter Type Description
includeUnicode bool Includes some Unicode alphabetic chars like accented letters. (Default: false)
errorMessage string Custom error message.

Examples


IsAlphanumeric

Validates if a string have only alphanumeric characters.

Parameters

Parameter Type Description
includeUnicode bool Includes some Unicode alphabetic chars like accented letters. (Default: false)
errorMessage string Custom error message.

Examples


IsBase64

Validates whether a string is in Base64 format.
Works with url safe base64 strings.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


IsCnpj

Validates if a given string has a valid CNPJ registration.

The Brazil National Registry of Legal Entities number (CNPJ) is a company identification number that must be obtained from the Department of Federal Revenue(Secretaria da Receita Federal do Brasil) prior to the start of any business activities.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples

[!IMPORTANT] The cnpj numbers above were generated randomly using this tool.
If one of them belongs to you, please send me a request to remove.


IsCpf

Validates if a given string has a valid CPF identification.

CPF Stands for “Cadastro de Pessoas Físicas” or “Registry of Individuals”. It is similar to the “Social Security” number adopted in the US, and it is used as a type of universal identifier in Brazil.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples

[!IMPORTANT] The CPF numbers above were generated randomly using this tool.
If one of them belongs to you, please send me a request and I will remove it immediately.


IsEmail

Validates whether a string has a valid email structure.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples

[!TIP] Take a look at the tests to see more of valid or invalid emails.


IsIP

Validates whether a string is a valid IP address for both V4 and V6.

Parameters

Parameter Type Description
version int 4 for IPv4 or 6 for IPv6, any other value tries to validate both.
errorMessage string Custom error message.

Examples


IsSemVer

Validates whether a version number follow the rules of semantic versioning (SemVer).

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


IsTUID

Validates whether a string is a valid TUID.

Parameters

Parameter Type Description
errorMessage string Custom error message.

Examples


IsURL

Validates whether a string has a valid URL structure.

Parameters

Parameter Type Description
options Torugo\TString\Options\UrlOptions Validation options.
errorMessage string Custom error message.

Validation Options

Default values:

Examples


Length

Validates if the length of a string is between a minimum and maximum parameters.

Parameters

Parameter Type Description
min int Minimum acceptable length. (must be >= 0).
max int Maximum acceptable length. (must be >= 1)
errorMessage string Custom error message.

Examples


Matches

Performs a regular expression match on property's value

Parameters

Parameter Type Description
pattern string The regex pattern to search for, as a string.
errorMessage string Custom error message.

Examples


MaxLength

Validates if the length of a string is lesser than or equal to a maximum parameter.

Parameters

Parameter Type Description
max int Maximum acceptable length. (must be >= 1)
errorMessage string Custom error message.

Examples


MinLength

Parameter Type Description
min int Minimum acceptable length. (must be >= 1)
errorMessage string Custom error message.

Examples


NotContains

Checks whether a substring is contained in the received value, if so, throws an exception.

Parameters

Parameter Type Description
substring string The substring to search for in the property's value.
caseSensitive bool Case sensitiveness. (Default: true)
errorMessage string Custom error message.

Examples


Handlers

Set of attributes that modify the value of a property and do not validate the value, the objective is to transform/manipulate them in some way.

When the type of the value is incorrect, the handlers should do nothing, so they normally do not throw any exceptions in this cases.

Some handlers require the property to be of a certain type, usually mixed, therefore they can throw InvalidTypeException.

Common

CopyFrom

Copies the value of another property in the same class.

Parameters

Parameter Type Description
target string Name of the property in the same class, whose value will be copied.

[!IMPORTANT] Throws InvalidArgumentException if the target properthy does not exists.

Example


Convertions

Explode

Explode is an alias to Split handler.


Implode

Implode is an alias to Join handler.


Join

Converts an array to a string by recursively joining the values ​​by placing a separator between them.

[!NOTE] This handler requires the property to be declared as mixed, otherwise InvalidTypeException will be thrown.

Parameters

Parameter Type Description
separator string To be placed between each array value. (Default '')
includeKeys bool Include key before each array value. (Default false)
keySeparator string To be placed between the key and value. (Default :)

Examples


Split

Converts a string to an array of strings each of which is a substring of it on boundaries formed by the string separator.

[!NOTE] This handler requires the property to be declared as mixed, otherwise InvalidTypeException will be thrown.

Parameters

Parameter Type Description
separator string The boundary string.
limit int* (Default: PHP_INT_MAX)

* If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. If the limit parameter is negative, all components except the last - limit are returned. If the limit parameter is zero, then this is treated as 1.

Examples


Strings

Append

Concatenates a string at the end of the property value.

Parameters

Parameter Type Description
append string String to be concatenated

Examples


PasswordHash

Generates a new password hash using a strong one-way hashing algorithm.
Uses PHP password_hash() function.

Parameters

Parameter Type Description
algo int|string|null A password algorithm constant denoting the algorithm to use when hashing the password.
options string An associative array containing options. See the password algorithm constants for documentation on the supported options for each algorithm. If omitted, a random salt will be created and the default cost will be used.

Examples


Prepend

Concatenates a string at the beginning of the property value.

Parameters

Parameter Type Description
prepend string String to be concatenated

Examples


SubString

Returns the portion of string specified by the offset and length parameters.
Uses PHP substr() function.

Parameters

Parameter Type Description
offset int If offset is non-negative, the returned string will start at the offset'th position in string, counting from zero. For instance, in the string ' abcdef', the character at position 0 is ' a', the character at position 2 is ' c', and so forth. If offset is negative, the returned string will start at the offset'th character from the end of string. If string is less than offset characters long, an empty string will be returned. Example #1 Using a negative offset
length int or null If length is given and is positive, the string returned will contain at most length characters beginning from offset (depending on the length of string). If length is given and is negative, then that many characters will be omitted from the end of string (after the start position has been calculated when a offset is negative). If offset denotes the position of this truncation or beyond, an empty string will be returned. If length is given and is 0, an empty string will be returned. If length is omitted or null, the substring starting from offset until the end of the string will be returned.

Examples


Replace

Replace all occurrences of the search string with the replacement string.

Parameters

Parameter Type Description
search string or array The value being searched for. An array may be used to designate multiple values.
replace string or array The replacement value that replaces found search values. An array may be used to designate multiple replacements.

Examples


ToLowerCase

Converts a string or string elements in an array to lower case.

Examples


ToTitleCase

Converts a string or string elements in an array to title case.

Parameters

Parameter Type Description
fixRomanNumerals bool Keep roman numerals uppercased (up to 6 digits). (Default: false)
fixPortuguesePrepositions bool Keep portuguese prepositions in lowercase. (Default: false)

To know more visit.

Examples


ToUpperCase

Converts a string or string elements in an array to upper case.

Examples


Trim, LTrim and RTrim

Strip whitespace (or other characters) from the beginning and end of a string.

Characters parameter

The stripped characters can be specified using the characters parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.

Examples

[!NOTE] LTrim and RTrim works exactly in the same way.


Setters

SetDateTime

Sets the property's value as DateTime object or formatted string.

Parameters

Parameter Type Description
datetime string A date/time string. Valid formats are explained in Date and Time Formats.
format string|null If provided, the value will be setted as a formatted string.
timezone DateTimeZone|null A DateTimeZone object representing the timezone of $datetime. If $timezone is omitted or null, the current timezone will be used.

Examples


SetFromCallback

Sets the property's value from a returned value of a function or class method. This attribute wraps the PHP call_user_func_array function.

Parameters

Parameter Type Description
callback string|array The callable to be called.
args array The parameters to be passed to the callback, as an array.

[!NOTE] If you want to call a method from a class, the method must be static.

Examples


SetValueWhenEmpty

Sets a custom string value when property receives an empty string or a null value.

Parameters

Parameter Type Description
value String The value to be setted when property receives an empty string or null.

Examples


SetValueWhenNull

Sets a custom value when property receives a null value.

Parameters

Parameter Type Description
value mixed The value to be setted when property receives null.

Examples


Custom Validators

To create a custom validator is required:

  1. The validator must extends Torugo\PropertyValidator\Abstract\Validator;
  2. Add the attribute #[Attribute(Attribute::TARGET_PROPERTY)] to the class;
  3. Implement the method public function validation(mixed $value): void;

Templates

Simple validator

Validator with arguments

Validator class

The Validator class gives to you:

Properties

Property Type Description
propertyName string The name of the property
propertyType string The type of the property, if not declared it will be considered "mixed"
propertyValue mixed The value of the property

Methods

Method Description
expectPropertyTypeToBe(array\|string $expected): void Validates if the property type is the expected. (throws InvalidTypeException)
expectValueTypeToBe(array\|string $expected): void Validates if the property value type is the expected. (throws InvalidTypeException)
hasAttribute(string $attrClass): bool Checks if the property has a specified attribute.
isNullable(): bool Checks if the property is nullable.
isUsingIsOptionalAttribute(): bool Checks if the property is using the #[IsOptional()] attribute.
isUsingRequiredAttribute(): bool Checks if the property is using the #[IsRequired()] attribute.
throwInvalidTypeException(string $message, int $code = 0): never Throws InvalidTypeException using the validator's default message or the custom error message defined on constructor.
throwValidationException(string $message, int $code = 0): never Throws ValidationException using the validator's default message or the custom error message defined on constructor.

Contribute

It is currently not open to contributions, I intend to make it available as soon as possible.

License

This library is licensed under the MIT License - see the LICENSE file for details.


All versions of property-validator with dependencies

PHP Build Version
Package Version
Requires torugo/tstring Version ^1.0.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package torugo/property-validator contains the following files

Loading the files please wait ....