A simple validation library that allows you to write custom validators for your data.
- PHPValidation
- Table of Contents
- Features
- Installation
- Usage
- Available field validators
- required
- notEmpty
- isArray
- hasKeys
- hasValues
- confirmValues
- in
- notIn
- minLength
- maxLength
- minCount
- maxCount
- phoneNumber
- isAlphabetic
- isNumeric
- isAlphaNumeric
- isInt
- isFloat
- isString
- isObject
- objectOfType
- equals
- contains
- greaterThan
- greaterEqual
- lowerThan
- lowerEqual
- between
- isDate
- dateHasFormat
- dateEquals
- dateLowerThan
- dateLowerEqual
- dateGreaterThan
- dateGreaterEqual
- dateBetween
PHPValidation comes with the following features:
- Array validation through a simple and clean interface
- Custom field validator support
- Built-in field validators for basic use-cases
requiredfield validatornotEmptyfield validator for strings and arraysisArrayfield validatorhasKeysfield validator for arrayshasValuesfield validator for arraysconfirmValuesfield validator for arraysinfield validator for strings, floats, integers, booleans, and arrays with the previous types inside of themnotInfield validator for strings, floats, integers, and booleansminLengthfield validator for stringsmaxLengthfield validator for stringsminCountfield validator for arraysmaxCountfield validator for arraysemailfield validator for stringsphoneNumberfield validator for stringsisAlphabeticfield validator for stringsisNumericfield validator for strings, floats, and integersisAlphaNumericfield validator for stringsisIntfield validator for strings and integersisFloatfield validator for strings, floats, and integersisStringfield validator for stringsisObjectfield validator for objectsequalsfield validator for any given data typecontainsfield validator for stringsgreaterThanfield validator for numeric strings, floats, and integersgreaterEqualfield validator for numeric strings, floats, and integerslowerThanfield validator for numeric strings, floats, and integerslowerEqualfield validator for numeric strings, floats, and integersbetweenfield validator for numeric strings, floats, and integersisDatefield validator for date strings and objects that implement the DateTimeInterface interfacedateHasFormatfield validator for date strings and objects that implement the DateTimeInterface interfacedateEqualsfield validator for date strings and objects that implement the DateTimeInterface interfacedateLowerThanfield validator for date strings and objects that implement the DateTimeInterface interfacedateLowerEqualfield validator for date strings and objects that implement the DateTimeInterface interfacedateGreaterThanfield validator for date strings and objects that implement the DateTimeInterface interfacedateGreaterEqualfield validator for date strings and objects that implement the DateTimeInterface interfacedateBetweenfield validator for date strings and objects that implement the DateTimeInterface interface
$ composer require guyliangilsing/php-validationIMPORTANT: PHPValidation requires php version 8 or higher to work properly.
A validator can be obtained through the ValidatorBuilder class:
use PHPValidation\Builders\ValidatorBuilder;
use PHPValidation\Strategies\DefaultValidationStrategy;
$strategy = new DefaultValidationStrategy();
$builder = new ValidatorBuilder($strategy);
// Your configuration logic here...
$validator = $builder->build();The validator builder has the following options:
use PHPValidation\Builders\ValidatorBuilder;
use PHPValidation\Strategies\DefaultValidationStrategy;
use PHPValidation\Validator;
use function PHPValidation\Functions\required;
$strategy = new DefaultValidationStrategy();
$builder = new ValidatorBuilder($strategy);
// Configures the field validators for each array field
$builder->setValidators([
'field1' => [required()],
]);
// Configures custom error messages for each array field validator
$builder->setErrorMessages([
'field1' => [
required()->getKey() => "My custom error message...",
]
]);
// Passes a new validation handler/strategy to the actual validator
$newStrategy = // Your custom strategy here...
$builder->setStrategy($newStrategy);
// Registers a new validator class that will be returned when you build the validator
$builder->setValidatorClassName(Validator::class);
$validator = $builder->build();Note: The builder already comes preconfigured with a strategy and validator class name, the example above just lists all possible configuration options.
A validator can also be obtained through the default factory:
namespace PHPValidation\Factories\ValidatorFactory;
$factory = new ValidatorFactory();
$validator = $factory->createDefaultValidator();Note: Adding more methods to this default factory class is possible by inheriting it.
Within the validation builder, an array must be set that defines how a given array should be validated. This uses the following structure:
[
'fieldName' => [FieldValidatorInterface, FieldValidatorInterface, FieldValidatorInterface],
'nestedField' => [
'fieldName' => [FieldValidatorInterface, FieldValidatorInterface, FieldValidatorInterface],
]
]The structure itself is quite simple. It is just an array that defines the names of the fields through keys, and the field validation through classes that implement the FieldValidatorInterface interface. Nested fields are also supported, you just have a key point to an array with the basic key => array<FieldValidatorInterface> structure, this can be done infinitely.
Each built-in field validator comes with their own default error messages. These messages can be overriden by providing the builder with an array that has the following structure:
[
'fieldName' => [
'fieldValidatorKey' => "Your custom error message..."
],
'nestedField' => [
'fieldName' => [
'fieldValidatorKey' => "Your custom error message..."
],
],
]This structure needs a field name key that points to an array that has the field validator key and an error message as a key => value pair. Nested fields are also supported and can be used by wrapping the structure for a singular field, inside an array that gets pointed to by a key.
Once you have configured the validator builder, the validator can be built by using the build() method:
use PHPValidation\Builders\ValidatorBuilder;
use PHPValidation\Strategies\DefaultValidationStrategy;
$strategy = new DefaultValidationStrategy();
$builder = new ValidatorBuilder($strategy);
// Your configuration logic here...
$validator = $builder->build();The validator can then be used to validate an array:
use PHPValidation\Builders\ValidatorBuilder;
use PHPValidation\Strategies\DefaultValidationStrategy;
use function PHPValidation\Functions\required;
$strategy = new DefaultValidationStrategy();
$builder = new ValidatorBuilder($strategy);
$builder->setValidators([
'field1' => [required()],
]);
$validator = $builder->build();
$isValid = $validator->isValid([]); // Will return false
$errorMessages = $validator->getErrorMessages(); // Will return error messagesCreating a custom field validator is quite easy. The only thing you have to do is implement the FieldValidatorInterface interface:
declare(strict_types=1);
namespace PHPValidation\Fields;
final class RequiredField implements FieldValidatorInterface
{
// Is used by the validation strategy and will skip this validator if it needs an existing field
public function fieldNeedsToExist(): bool
{
return false;
}
// The unique key for this validator
public function getKey(): string
{
return 'required';
}
// Your validation logic goes here...
public function isValid(bool $fieldExists, mixed $fieldData, array $givenData): bool
{
return $fieldExists;
}
// Your default error message goes here...
public function getErrorMessage(): string
{
return 'This field is required';
}
}It is recommended to create a simple function that wraps your custom validator. PHPValidation comes with some basic built-in validators that are being wrapped in the following way:
declare(strict_types=1);
namespace PHPValidation\Functions;
use PHPValidation\Fields\FieldValidatorInterface;
use PHPValidation\Fields\RequiredField;
function required(): FieldValidatorInterface
{
return new RequiredField();
}Wrapping your custom validator with a function will prevent the following code from being written:
use PHPValidation\Builders\ValidatorBuilder;
use PHPValidation\Strategies\DefaultValidationStrategy;
use PHPValidation\Validator;
$strategy = new DefaultValidationStrategy();
$builder = new ValidatorBuilder($strategy);
$builder->setValidators([
'field1' => [new RequiredField(), new CustomValidator()],
]);
$validator = $builder->build();And makes the final code easier to read:
use PHPValidation\Builders\ValidatorBuilder;
use PHPValidation\Strategies\DefaultValidationStrategy;
use PHPValidation\Validator;
use function PHPValidation\Functions\required;
$strategy = new DefaultValidationStrategy();
$builder = new ValidatorBuilder($strategy);
$builder->setValidators([
'field1' => [required(), custom_validator()],
]);
$validator = $builder->build();PHPValidation comes with some built-in field validators that should cover basic use cases.
When added, this field key must be present in an array.
$builder->setValidators([
'field' => [required()],
]);When added, and the field exists, and the field is of the type string or array, it cannot be empty or contain only whitespace.
$builder->setValidators([
'field' => [notEmpty()],
]);When added, and the field exists, it must be of the type array.
$builder->setValidators([
'field' => [isArray()],
]);When added, and the field exists, and the field is of the type array, it must have all of the stated keys.
$builder->setValidators([
'field' => [hasKeys('key1', 'key2', 'key3')],
]);When added, and the field exists, and the field is of the type array, it must have all of the stated values.
$builder->setValidators([
'field' => [hasValues(['value1', 'value2', 'value3'])],
]);When added, and the field exists, the field value must be equal to the value of another field. When specifying which array field value the current field must match, dot notation is used to denote the key tree: key1.nestedKey1 translates to the following php array:
[
'key1' => [
'nestedKey1' => // YOUR VALUE HERE...
],
]$builder->setValidators([
'field1' => [confirmValues('field2')], // Targets the key on the first array level
'field2' => [confirmValues('field2.nestedField1')], // Targets the key on the second array level
]);When added, and the field exists, and the field is of the type string, int, float, bool, or array, it can only contain one of the stated values.
Note: When this validator has an array value passed to it, it will only validate the first level of the array.
$builder->setValidators([
'field' => [in(['option1', 'option2', 'option3'])],
]);When added, and the field exists, and the field is of the type string, int, float, or bool, it cannot contain one of the stated values.
$builder->setValidators([
'field' => [notIn(['option1', 'option2', 'option3'])],
]);When added, and the field exists, and the field is of the type string, it must have a minimum amount of characters.
$builder->setValidators([
'field' => [minLength(5)],
]);When added, and the field exists, and the field is of the type string, it cannot have more than a certain amount of characters.
$builder->setValidators([
'field' => [maxLength(10)],
]);When added, and the field exists, and the field is of the type array, it must have a minimum amount of values.
$builder->setValidators([
'field' => [minCount(2)],
]);When added, and the field exists, and the field is of the type array, it cannot have more than a certain amount of values.
$builder->setValidators([
'field' => [maxCount(4)],
]);When added, and the field exists, and the field is of the type string, it will check for an RFC 5322 compliant email address.
$builder->setValidators([
'field' => [email()],
]);When added, and the field exists, and the field is of the type string, it will check for a valid international phone number.
Note: This validator does not accept phone numbers delimitted by any characters and/or whitespace.
Note: It probably will be better to create your own phone number validator since a phone number can differ greatly depending on the country/location.
$builder->setValidators([
'field' => [phoneNumber()],
]);When added, and the field exists, and the field is of the type string, it will check if its value only contains normal, non-special, characters and whitespace.
$builder->setValidators([
'field' => [isAlphabetic()],
]);When added, and the field exists, and the field is of the following types: string, float, or int, it will check if the given value is numeric.
$builder->setValidators([
'field' => [isNumeric()],
]);When added, and the field exists, and the field is of the type string, it will check if the given value only contains normal, non-special, characters, numbers, and whitespace. The validator also supports whitelisting extra characters.
$builder->setValidators([
'normalField' => [isAlphaNumeric()],
'extraField' => [isAlphaNumeric(['.', ',', '\\', '[', ']'])], // Whitelists each individual character within the array
]);When added, and the field exists, and the field is of the following types: string or int, it will check if the given value can be converted to an integer, and thus is an integer.
$builder->setValidators([
'field' => [isInt()],
]);When added, and the field exists, and the field is of the following types: string, float, or int, it will check if the given value can be converted to a float without losing any data, and thus is an float.
$builder->setValidators([
'field' => [isFloat()],
]);When added, and the field exists, it will check if the given value is of the type string.
$builder->setValidators([
'field' => [isString()],
]);When added, and the field exists, it will check if the given value is of the type object.
$builder->setValidators([
'field' => [isObject()],
]);When added, and the field exists, and the field is of the type object, it will check if the given value has a desired object type.
$builder->setValidators([
'field' => [objectOfType(DateTime::clas)],
]);When added, and the field exists, it will check if the given value matches the field value. This validator supports strict and non-strict value validation.
$builder->setValidators([
'nonStrictField' => [equals('non-strict', false)],
'strictField' => [equals('strict', true)],
]);When added, and the field exists, and the field is of the type string, it will check if the given value contains a specific substring.
$builder->setValidators([
'field' => [contains('substring')],
]);When added, and the field exists, and the field is of the following types: string, float, or int, it will check if the given value is greater than the field value.
$builder->setValidators([
'field' => [greaterThan(30)],
]);When added, and the field exists, and the field is of the following types: string, float, or int, it will check if the given value is greater than, or equal to, the field value.
$builder->setValidators([
'field' => [greaterEqual(30)],
]);When added, and the field exists, and the field is of the following types: string, float, or int, it will check if the given value is lower than the field value.
$builder->setValidators([
'field' => [lowerThan(30)],
]);When added, and the field exists, and the field is of the following types: string, float, or int, it will check if the given value is lower than, or equal to, the field value.
$builder->setValidators([
'field' => [lowerEqual(30)],
]);When added, and the field exists, and the field is of the following types: string, float, or int, it will check if the given value is between two given values.
$builder->setValidators([
'field' => [between(0, 100)],
]);When added, and the field exists, and the field is of the following type string or implements the DateTimeInterface interface, it will check if the field is a date string or an object that implements the DateTimeInterface interface.
Note: This field uses php's strtotime() function to check if a string is indeed a date string.
$builder->setValidators([
'field' => [isDate()],
]);When added, and the field exists, and the field is of the following type string or implements the DateTimeInterface interface, it will check if the field uses a given php datetime format.
Note: It is recommended to only use this validator with date strings. Objects that implement the DateTimeInterface interface will always be valid since they are internally cast back to a string with the given format.
$builder->setValidators([
'field' => [dateHasFormat('Y-m-d')],
]);When added, and the field exists, and the field is of the following type string or implements the DateTimeInterface interface, it will check if the field value is equal to a pre-determined date object.
$builder->setValidators([
'field' => [dateEquals(DateTime::createFromFormat('Y-m-d', '2000-12-31'), 'Y-m-d')],
]);When added, and the field exists, and the field is of the following type string or implements the DateTimeInterface interface, it will check if the given value is lower than the field value.
$builder->setValidators([
'field' => [dateLowerThan(DateTime::createFromFormat('Y-m-d', '2000-12-31'), 'Y-m-d')],
]);When added, and the field exists, and the field is of the following type string or implements the DateTimeInterface interface, it will check if the given value is lower than, or equal to, the field value.
$builder->setValidators([
'field' => [dateLowerEqual(DateTime::createFromFormat('Y-m-d', '2000-12-31'), 'Y-m-d')],
]);When added, and the field exists, and the field is of the following type string or implements the DateTimeInterface interface, it will check if the given value is greater than the field value.
$builder->setValidators([
'field' => [dateGreaterThan(DateTime::createFromFormat('Y-m-d', '2000-12-31'), 'Y-m-d')],
]);When added, and the field exists, and the field is of the following type string or implements the DateTimeInterface interface, it will check if the given value is greater than, or equal to, the field value.
$builder->setValidators([
'field' => [dateGreaterEqual(DateTime::createFromFormat('Y-m-d', '2000-12-31'), 'Y-m-d')],
]);When added, and the field exists, and the field is of the following type string or implements the DateTimeInterface interface, it will check if the given value is between two given dates.
$dateMin = DateTime::createFromFormat('Y-m-d', '2000-12-29');
$dateMax = DateTime::createFromFormat('Y-m-d', '2000-12-30');
$builder->setValidators([
'field' => [dateBetween($dateMin, $dateMax, 'Y-m-d')],
]);