Validate
The Validate
class provides a simple, static method to validate data against a set of rules. It's used throughout the SchoolKit modules to ensure data integrity.
Quick Reference
validate()
validate(array $data, array $rules): array
Validates data against rules and throws exception on failure
Methods
validate
validate(array $data, array $rules): array
Validates an array of data against a set of rules. If validation fails, it throws an InvalidArgumentException
with a JSON-encoded list of errors.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$data |
array |
Yes | The associative array of data to validate (e.g., $_POST ). |
$rules |
array |
Yes | An associative array where keys match the data keys and values are validation rules. |
Returns
The original $data
array if validation is successful.
Example
<?php
require_once 'schoolkit.php';
$input = [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'age' => '30',
'status' => 'active'
];
$rules = [
'name' => 'required|string|min:2',
'email' => 'required|email',
'age' => 'required|int|min:18',
'status' => 'in:active,inactive'
];
try {
$validatedData = Skhoolar_SchoolKit_Core_Validate::validate($input, $rules);
echo "All data is valid!";
print_r($validatedData);
} catch (InvalidArgumentException $e) {
echo "Validation failed: " . $e->getMessage();
}
?>
Available Rules
Rules can be provided as a pipe-separated string or as an array of strings.
Rule | Description | Example |
---|---|---|
required | The field must not be null, an empty string, or an empty array. | 'name' => 'required' |
string | The field must be a string. | 'name' => 'string' |
int | The field must be a valid integer. | 'age' => 'int' |
numeric | The field must be numeric. | 'score' => 'numeric' |
email | The field must be a valid email address. | 'user_email' => 'email' |
bool | The field must be a boolean value (true, false, 1, 0, '1', '0'). | 'is_active' => 'bool' |
date | The field must be a valid date in YYYY-MM-DD format. | 'start_date' => 'date' |
datetime | The field must be a valid datetime in YYYY-MM-DD HH:MM:SS format. | 'event_time' => 'datetime' |
min:X | The field's length (string), value (numeric), or count (array) must be at least X. | 'password' => 'min:8' |
max:X | The field's length (string), value (numeric), or count (array) must not exceed X. | 'bio' => 'max:500' |
in:a,b,c | The field's value must be one of the specified values. | 'status' => 'in:pending,approved,rejected' |