PHP Validator is a fast, extensible, and simple PHP validation library that allows you to easily validate various types of data.
You can install this library via Composer. Ensure your project meets the minimum PHP version requirement of 7.4.
composer require phpdevcommunity/php-validator- PHP version 7.4 or higher
- Required package for PSR-7 HTTP Message (e.g.,
guzzlehttp/psr7)
The PHP Validator library enables you to validate data in a simple and flexible manner using pre-configured validation rules. Here are some usage examples:
Validate an email address to ensure it is not null and matches the standard email format.
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Email;
// Instantiate Validation object for email validation$validation = newValidation([
'email' => [newNotNull(), newEmail()]
]);
// Example data array$data = ['email' => 'john.doe@example.com'];
// Validate the dataif ($validation->validateArray($data) === true) {
echo"Email is valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . implode(", ", $errors['email']);
}Validate the age to ensure it is a non-null integer and is 18 or older.
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Integer;
// Instantiate Validation object for age validation$validation = newValidation([
'age' => [newNotNull(), newInteger(['min' => 18])]
]);
// Example data array$data = ['age' => 25];
// Validate the dataif ($validation->validateArray($data) === true) {
echo"Age is valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . implode(", ", $errors['age']);
}By default, when using validate(ServerRequestInterface $request), the convertEmptyToNull option is automatically enabled.
This ensures that all empty strings ("") are converted to null before validation.
When using validateArray(array $data) directly, you need to enable this option manually:
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Item;
usePhpDevCommunity\Validator\Assert\Alphabetic;
// Define validation rules$validation = newValidation([
'person' => [newNotNull(), newItem([
'first_name' => [newNotNull(), newAlphabetic()],
'last_name' => [newNotNull(), newAlphabetic()],
])]
]);
// Example input with an empty string$validInput = [
'person' => [
'first_name' => '', // will be converted to null'last_name' => 'Doe'
]
];
// Manually enable conversion of "" to null$validation->convertEmptyToNull();
if ($validation->validateArray($validInput) === true) {
echo"Data is valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . json_encode($errors, JSON_PRETTY_PRINT);
}In this example:
- Before validation, empty strings are converted to
null. - This prevents validators such as
NotNull()from failing because of an empty string. - When using
validate($request)with a PSR-7 request, this option is automatically enabled.
Let's explore more examples covering various validators:
Ensure that a username is not null, has a minimum length of 3 characters, and contains only alphanumeric characters.
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Alphanumeric;
usePhpDevCommunity\Validator\Assert\StringLength;
// Instantiate Validation object for username validation$validation = newValidation([
'username' => [newNotNull(), newStringLength(['min' => 3]), newAlphanumeric()]
]);
// Example data array$data = ['username' => 'john_doe123'];
// Validate the dataif ($validation->validateArray($data) === true) {
echo"Username is valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . implode(", ", $errors['username']);
}The Item rule allows you to validate nested objects or associative arrays with specific rules for each key.
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Item;
usePhpDevCommunity\Validator\Assert\StringLength;
usePhpDevCommunity\Validator\Assert\Alphabetic;
// Define validation rules for a nested object (e.g., a "person" object)$validation = newValidation([
'person' => [newNotNull(), newItem([
'first_name' => [newNotNull(), newAlphabetic(), (newStringLength())->min(3)],
'last_name' => [newNotNull(), newAlphabetic(), (newStringLength())->min(3)],
])]
]);
// Example data$data = [
'person' => [
'first_name' => 'John',
'last_name' => 'Doe'
]
];
// Validate the dataif ($validation->validateArray($data) === true) {
echo"Person object is valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . json_encode($errors, JSON_PRETTY_PRINT);
}The Collection rule is used to validate arrays where each item in the array must satisfy a set of rules.
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotEmpty;
usePhpDevCommunity\Validator\Assert\Collection;
usePhpDevCommunity\Validator\Assert\Item;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\StringLength;
// Define validation rules for a collection of articles$validation = newValidation([
'articles' => [newNotEmpty(), newCollection([
newItem([
'title' => [newNotNull(), (newStringLength())->min(3)],
'body' => [newNotNull(), (newStringLength())->min(10)],
])
])]
]);
// Example data$data = [
'articles' => [
['title' => 'Article 1', 'body' => 'This is the body of the first article.'],
['title' => 'Article 2', 'body' => 'Second article body here.']
]
];
// Validate the dataif ($validation->validateArray($data) === true) {
echo"Articles are valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . json_encode($errors, JSON_PRETTY_PRINT);
}Validate a URL to ensure it is not null and is a valid URL format.
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Url;
// Instantiate Validation object for URL validation$validation = newValidation([
'website' => [newNotNull(), newUrl()]
]);
// Example data array$data = ['website' => 'https://example.com'];
// Validate the dataif ($validation->validateArray($data) === true) {
echo"Website URL is valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . implode(", ", $errors['website']);
}Validate a numeric value to ensure it is not null and represents a valid numeric value.
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Numeric;
// Instantiate Validation object for numeric value validation$validation = newValidation([
'price' => [newNotNull(), newNumeric()]
]);
// Example data array$data = ['price' => 99.99];
// Validate the dataif ($validation->validateArray($data) === true) {
echo"Price is valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . implode(", ", $errors['price']);
}Implement a custom validation rule using a callback function.
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Custom;
// Custom validation function to check if the value is a boolean$isBoolean = function ($value) {
returnis_bool($value);
};
// Instantiate Validation object with a custom validation rule$validation = newValidation([
'active' => [newNotNull(), newCustom($isBoolean)]
]);
// Example data array$data = ['active' => true];
// Validate the dataif ($validation->validateArray($data) === true) {
echo"Value is valid!";
} else {
$errors = $validation->getErrors();
echo"Validation errors: " . implode(", ", $errors['active']);
}Certainly! Below is a chapter you can add to your README specifically covering examples for using the validate(ServerRequestInterface $request) method from your Validation class.
The Validation class provides a convenient method validate(ServerRequestInterface $request) to validate data extracted from a \Psr\Http\Message\ServerRequestInterface object. This method simplifies the process of validating request data typically received in a web application.
Suppose you have a user registration form with fields like username, email, password, and age. Here's how you can use the validate method to validate this form data:
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Email;
usePhpDevCommunity\Validator\Assert\Integer;
// Define validation rules for each field$validation = newValidation([
'username' => [newNotNull()],
'email' => [newNotNull(), newEmail()],
'password' => [newNotNull()],
'age' => [newNotNull(), newInteger()]
]);
// Assume $request is the \Psr\Http\Message\ServerRequestInterface object containing form dataif ($validation->validate($request) === true) {
// Validation passed, retrieve validated data$validatedData = $validation->getData();
// Process registration logic here (e.g., save to database)// $username = $validatedData['username'];// $email = $validatedData['email'];// $password = $validatedData['password'];// $age = $validatedData['age'];echo"Registration successful!";
} else {
// Validation failed, retrieve validation errors$errors = $validation->getErrors();
// Handle validation errors (e.g., display error messages to the user)echo"Validation errors: " . implode(", ", $errors);
}In this example:
- We instantiate a
Validationobject with validation rules defined for each field (username,email,password,age). - We call the
validatemethod with the$requestobject containing form data. - If validation passes (
validatemethod returnstrue), we retrieve the validated data using$validation->getData()and proceed with the registration logic. - If validation fails, we retrieve the validation errors using
$validation->getErrors()and handle them accordingly.
Consider validating input data received via an API endpoint. Here's how you can use the validate method in this context:
usePhpDevCommunity\Validator\Validation;
usePhpDevCommunity\Validator\Assert\NotNull;
usePhpDevCommunity\Validator\Assert\Numeric;
// Define validation rules for API input data$validation = newValidation([
'product_id' => [newNotNull(), newNumeric()],
'quantity' => [newNotNull(), newNumeric()]
]);
// Assume $request is the \Psr\Http\Message\ServerRequestInterface object containing API input dataif ($validation->validate($request) === true) {
// Validation passed, proceed with processing API request$validatedData = $validation->getData();
// Extract validated data$productId = $validatedData['product_id'];
$quantity = $validatedData['quantity'];
echo"API request validated successfully!";
} else {
// Validation failed, retrieve validation errors$errors = $validation->getErrors();
// Handle validation errors (e.g., return error response to the client)echo"Validation errors: " . implode(", ", $errors);
}In this example:
- We define validation rules for
product_idandquantity. - We call the
validatemethod with the$requestobject containing API input data. - If validation passes, we retrieve the validated data using
$validation->getData()and proceed with processing the API request. - If validation fails, we retrieve the validation errors using
$validation->getErrors()and handle them appropriately.
- Simple Interface: Easily define validation rules using a straightforward interface.
- Extensible: Extend the library with custom validation rules by implementing the
ValidatorInterface. - Error Handling: Retrieve detailed validation errors for each field.
This library is open-source software licensed under the MIT license.