Validator
The Validator class provides a centralized mechanism for data integrity. It handles everything from simple type casting and string sanitization to complex, rule-based form validation.
Identity & Strings
string($value, bool $escape = true): string
Sanitizes input to a string. Trims whitespace and converts special chars to HTML entities (unless $escape is false).
email($value): ?string
Validates an email address. Returns null if invalid.
uuid($value): ?string
Validates standard UUID format.
ulid($value): ?string
Validates Universally Unique Lexicographically Sortable Identifier.
cuid($value) / cuid2($value)
Validates Collision-resistant Unique Identifiers (v1 and v2).
emojis(string $content): string
Converts shortcodes (e.g., :smile:) into actual unicode emoji characters.
Numbers & Math
Leverages Brick\Math for high-precision operations.
int($value): ?int
float($value): ?float
bigInt($value): ?BigInteger
Brick\Math\BigInteger object. Useful for values larger than PHP_INT_MAX.
decimal($value, int $scale): ?BigDecimal
Brick\Math\BigDecimal object with strict precision scaling.
bytes($value): ?string
Structure & Logic
json($value): string
Validates JSON strings or safely encodes arrays to JSON. Returns error message string on failure.
boolean($value): ?bool
Smart boolean casting (handles "true", "1", "on", "yes").
enum($value, array $allowed): bool
Checks if value exists within a simple array of allowed options.
enumClass($value, string $class)
Validates against a PHP BackedEnum class. Supports single values or arrays of values.
Rule-Based Validation
withRules($value, string $rules, $confirm = null)
Evaluates a value against a pipe-separated list of rules.
Returns true (strict boolean) if successful, or a string containing the error message if failed.
Available Rules
Usage Example
<?php
use PP\Validator;
use PP\StateManager;
// 1. Simple Type Check
$age = Validator::int("25"); // Returns 25 (int)
$email = Validator::email("invalid-email"); // Returns null
// 2. Rule Validation
$inputName = "John";
$validation = Validator::withRules($inputName, "required|min:3|max:50");
if ($validation === true) {
// Success
StateManager::setState('name', $inputName);
} else {
// Failure - $validation contains the error string (e.g. "This field is required.")
echo $validation;
}
// 3. Password Confirmation
$password = "secret123";
$confirm = "secret123";
$check = Validator::withRules($password, "required|min:8|confirmed", $confirm);
?>