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-validator
use BlakvGhost\PHPValidator\Validator;
use BlakvGhost\PHPValidator\ValidatorException;
try {
$data = [
'username' => 'BlakvGhost',
'email' => 'example@example.com',
'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 theRule
Interface. -
Multilingual Support
: Customize validation error messages based on the application's language using theLangManager
.
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
- Ensures that a field is present in the data.
'username' => 'required'
-
String Rule
- Checks if a field is of string type.
'username' => 'string'
-
Email Rule
- Validates that a field is a well-formed email address.
'email' => 'email'
-
Max Length Rule
- Specifies the maximum length of a string field.
'username' => 'max:25'
-
Confirmed Rule
- Checks if a field's value is the same as another field (commonly used for password confirmation).
'password_confirmation' => 'confirmed:password'
-
File Rule
- Validates that a field is a file upload.
'file' => 'file'
-
Accepted Rule
- Validates that a field is
"yes"
,"on"
,"1"
, ortrue
. Useful for checkboxes.
'terms_and_conditions' => 'accepted'
- Validates that a field is
-
Accepted If Rule
- Validates that a field is accepted if another field is equal to a specified value.
'terms_and_conditions' => 'accepted_if:is_adult,true'
-
ActiveURL Rule
- Validates that a field is a valid, active URL.
'website' => 'active_url'
-
Alpha Rule
- Validates that a field contains only alphabetic characters.
'name' => 'alpha'
-
Numeric Rule
- Validates that a field contains only numeric characters.
'age' => 'numeric'
-
Lowercase Rule
- Validates that a field contains only lowercase alphabetic characters.
'username' => 'lowercase'
-
Uppercase Rule
- Validates that a field contains only uppercase alphabetic characters.
'username' => 'uppercase'
-
In Rule
- Validates that a field's value is among a list of predefined values.
'role' => 'in:admin,editor,viewer'
-
Nullable Rule
- Allows a field to be
null
or empty.
'optional_field' => 'nullable'
- Allows a field to be
-
Password Rule
- Validates that a field is a
secure password
.
'password' => 'password'
- Validates that a field is a
-
Same Rule
- Validates that a field's value is the same as the value of another field.
'password_confirmation' => 'same:password'
-
Max Length Rule
- Specifies the minimum length of a string field.
'username' => 'min:8'
-
Not In Rule
- Validates that a field's value is not in a specified set.
'value' => 'not_in:foo,bar'
-
Required With Rule
- Requires the field to be present if another specified field is present.
'firstname' => 'required_with:lastname',
-
Valid IP Rule
- Validates that a field's value is a valid IP address.
'client_ip' => 'ip',
-
Json Rule
- Validates that a field's value is a valid JSON string.
'config' => 'json',
-
URL Rule
- Validates that a field's value is a valid URL.
'website' => 'url',
-
Alpha Numeric Rule
- Validates that a field's value contains only alphanumeric characters.
'pseudo' => 'alpha_num',
-
Boolean Rule
- Validates that a field's value is a boolean.
'is_admin' => 'bool',
-
Size Rule
- Validates that the size of a string, integer, array, or file is equal to a specified value.
[ '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
- Requires the field not be present if another specified field is present.
'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 YourNameSpace\Rules;
use BlakvGhost\PHPValidator\Contracts\Rule;
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 BlakvGhost\PHPValidator\Validator; use BlakvGhost\PHPValidator\ValidatorException; use YourNameSpace\CustomPasswordRule; // ... 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 BlakvGhost\PHPValidator\Validator; use BlakvGhost\PHPValidator\ValidatorException; use BlakvGhost\PHPValidator\Mapping\RulesMaped; use YourNameSpace\CustomPasswordRule; // 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 dev@username-blakvghost.com. 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.