PHPValidator is a modern PHP library for data validation in your PHP applications. It provides a flexible and extensible way to validate data using predefined rules or by creating custom validation rules.
Use Composer to install PHPValidator:
composer require blakvghost/php-validatoruse BlakvGhostPHPValidatorValidator;
use BlakvGhostPHPValidatorValidatorException;
try {
$data = [
'username' => 'BlakvGhost',
'email' => '[email protected]',
'score' => 42,
];
// or
// $data = $_POST;
$validator = new Validator($data, [
'username' => 'required|string',
'email' => 'required|email',
'score' => ['required','max:200', new CustomRule()],
'password' => new CustomRule(),
]);
if ($validator->isValid()) {
echo "Validation passed!";
} else {
$errors = $validator->getErrors();
print_r($errors);
}
} catch (ValidatorException $e) {
echo "Validation error: " . $e->getMessage();
}You can also customize the validation error messages or specify the default language
$data = [
'username' => 'BlakvGhost',
];
$validator = new Validator(
$data,
[
'username' => 'required|string',
],
[
'username' => [
'required' => 'Votre nom d'utilisateur doit être présent',
'string' => 'Votre nom d'utilisateur doit forcément être une chaîne de caractère',
],
]
);
// For the default language
$validator = new Validator($data, $rules, lang: 'fr');Predefined Rules: PHPValidator comes with a set of predefined validation rules such as required, string, email, maxLength etc.
Custom Rules: Easily create custom validation rules by implementing the Rule Interface.
Multilingual Support: Customize validation error messages based on the application's language using the LangManager.
PHPValidator provides a variety of predefined rules that you can use for data validation. Here is a list of some commonly used rules along with examples of their usage:
Required Rule
'username' => 'required'String Rule
'username' => 'string'Email Rule
'email' => 'email'Max Length Rule
'username' => 'max:25'Confirmed Rule
'password_confirmation' => 'confirmed:password'File Rule
'file' => 'file'Accepted Rule
"yes", "on", "1", or true. Useful for checkboxes.'terms_and_conditions' => 'accepted'Accepted If Rule
'terms_and_conditions' => 'accepted_if:is_adult,true'ActiveURL Rule
'website' => 'active_url'Alpha Rule
'name' => 'alpha'Numeric Rule
'age' => 'numeric'Lowercase Rule
'username' => 'lowercase'Uppercase Rule
'username' => 'uppercase'In Rule
'role' => 'in:admin,editor,viewer'Nullable Rule
null or empty.'optional_field' => 'nullable'Password Rule
secure password.'password' => 'password'Same Rule
'password_confirmation' => 'same:password'Max Length Rule
'username' => 'min:8'Not In Rule
'value' => 'not_in:foo,bar'Required With Rule
'firstname' => 'required_with:lastname',Valid IP Rule
'client_ip' => 'ip',Json Rule
'config' => 'json',URL Rule
'website' => 'url',Alpha Numeric Rule
'pseudo' => 'alpha_num',Boolean Rule
'is_admin' => 'bool',Size Rule
[
'string' =>'size:7', // strlen(string) == 7
'integer' =>'size:7', // integer == 7
'array' =>'size:7', // count(array) == 7
'file' =>'size:512', // file size (kb) == 512
]Not Required With Rule
'email' => 'not_required_with:phone_number',In addition to the predefined rules, you can create custom validation rules by implementing the Rule Interface. Here's an example of how to create and use a custom rule:
// CustomPasswordRule.php
namespace YourNameSpaceRules;
use BlakvGhostPHPValidatorContractsRule;
class CustomPasswordRule implements Rule
{
protected $field;
public function __construct(protected array $parameters = [])
{
}
public function passes(string $field, $value, array $data): bool
{
$this->field = $field;
// Implement your custom validation logic here
// Example: Check if the password is equal to confirm_password
return $value === $data['confirm_password'];
}
public function message(): string
{
return "Vos deux mot de passes ne sont pas identiques";
}
}Use your custom class directly
use BlakvGhostPHPValidatorValidator;
use BlakvGhostPHPValidatorValidatorException;
use YourNameSpaceCustomPasswordRule;
// ...
try {
$data = [
'password' => '42',
'confirm_password' => '142',
];
// or
// $data = $_POST;
$validator = new Validator($data, [
'password' => ['required', new CustomPasswordRule()],
]);
if ($validator->isValid()) {
echo "Validation passed!";
} else {
$errors = $validator->getErrors();
print_r($errors);
}
} catch (ValidatorException $e) {
echo "Validation error: " . $e->getMessage();
}Add your custom class to the rules list and use it as if it were native
use BlakvGhostPHPValidatorValidator;
use BlakvGhostPHPValidatorValidatorException;
use BlakvGhostPHPValidatorMappingRulesMaped;
use YourNameSpaceCustomPasswordRule;
// Add your rule here using an alias and the full namespace of your custom class
RulesMaped::addRule('c_password', CustomPasswordRule::class);
try {
$data = [
'password' => '42',
'confirm_password' => '142',
];
$validator = new Validator($data, [
'password' => 'required|c_password',
]);
if ($validator->isValid()) {
echo "Validation passed!";
} else {
$errors = $validator->getErrors();
print_r($errors);
}
} catch (ValidatorException $e) {
echo "Validation error: " . $e->getMessage();
}In this example, we created a CustomPasswordRule that checks if the password is equal to confirm_password. You can customize the passes method to implement your specific validation logic.
If you would like to contribute to PHPValidator, please follow our Contribution Guidelines.
For support, you can reach out to me by email at [email protected]. Feel free to contact me if you have any questions or need assistance with PHPValidator.
PHPValidator is open-source software licensed under the MIT license.