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

NameTypeRequiredDescription
$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.

RuleDescriptionExample
requiredThe field must not be null, an empty string, or an empty array.'name' => 'required'
stringThe field must be a string.'name' => 'string'
intThe field must be a valid integer.'age' => 'int'
numericThe field must be numeric.'score' => 'numeric'
emailThe field must be a valid email address.'user_email' => 'email'
boolThe field must be a boolean value (true, false, 1, 0, '1', '0').'is_active' => 'bool'
dateThe field must be a valid date in YYYY-MM-DD format.'start_date' => 'date'
datetimeThe field must be a valid datetime in YYYY-MM-DD HH:MM:SS format.'event_time' => 'datetime'
min:XThe field's length (string), value (numeric), or count (array) must be at least X.'password' => 'min:8'
max:XThe field's length (string), value (numeric), or count (array) must not exceed X.'bio' => 'max:500'
in:a,b,cThe field's value must be one of the specified values.'status' => 'in:pending,approved,rejected'