Validator
This document provides comprehensive details on the Validator
class, which is responsible for validating various data types. It includes functions for strings, integers, floats, booleans, date/time formats, JSON, and more, ensuring data integrity before processing or storage.
Purpose
The Validator
class aims to provide a centralized and consistent validation mechanism for various data types across the application, thus preventing invalid data from causing errors or security issues downstream.
Methods
Each method in the Validator
class corresponds to a specific data type or validation rule, detailed below:
string($value)
: Sanitizes and trims a string, converting special characters to HTML entities.int($value)
: Validates and returns an integer value, or null if validation fails.float($value)
: Validates and returns a floating-point number, or null if validation fails.boolean($value)
: Returns a boolean value or null if the input does not represent a boolean.date($value, string $format = 'Y-m-d')
: Validates a date format (e.g., 'Y-m-d').dateTime($value, $format = 'Y-m-d H:i:s')
: Checks if the value matches a 'Y-m-d H:i:s' format and returns it if valid, otherwise returns null.json($value)
: Verifies if the value is a valid JSON string.bigInt($value)
: Validates integers, identical toint
validation.bytes($value)
: Validates size strings like "10MB".decimal($value)
: Validates decimal values, identical tofloat
validation.enum($value, array $allowedValues)
: Ensures the value is one of the allowed enumerated values.email($value)
: Validates an email address format.url($value)
: Validates a URL format.uuid($value)
: Validates a UUID string.cuid($value)
: Validates a CUID string.ip($value)
: Validates an IP address.xml($value)
: Validates an XML string.html(string $html)
: Validates and sanitizes HTML content.emojis(string $emojis)
: Validates and sanitizes emoji characters.withRules(value, rule, confirmedValue)
: Validates a value against a set of rules.
Example Usage
Validating User Input
<?php
use Lib\Validator;
$email = 'user@example.com';
$isValidEmail = Validator::email($email);
$age = '30';
$isValidAge = Validator::int($age);
echo "<pre>";
echo "Email validated: " . ($isValidEmail ?? 'Invalid email') . "\n";
echo "Age validated: " . ($isValidAge !== null ? 'Yes' : 'No');
echo "</pre>";
Validating in if Statements
<?php
use Lib\Validator;
$name = 'John Doe';
if (Validator::string($name)) {
echo "Name is valid";
} else {
echo "Name is invalid";
}
$age = '30';
if (Validator::int($age)) {
echo "Age is valid";
} else {
echo "Age is invalid";
}
?>
Validating user input is a common use case for the Validator
class. In this example, we validate an email address and an age value using the email
and int
methods, respectively. The results are then displayed using echo
statements. The email
method returns the validated email address or null
if invalid, while the int
method returns the integer value or null
if validation fails.
Validating Inputs in a Form
<?php
use Lib\StateManager;
use Lib\Validator;
$message = StateManager::getState('message', ['status' => false, 'message' => '']);
function validateName($data)
{
global $state;
$name = $data->name;
if (!Validator::string($name)) {
StateManager::setState('message', ['status' => false, 'message' => 'Name must be a string']);
} else if (strlen($name) < 3) {
StateManager::setState('message', ['status' => false, 'message' => 'Name must be at least 3 characters']);
} else if (strlen($name) > 255) {
StateManager::setState('message', ['status' => false, 'message' => 'Name must be at most 255 characters']);
} else {
StateManager::setState('message', ['status' => true, 'message' => 'Name is valid']);
}
}
?>
<div class="w-screen h-screen grid place-items-center">
<div class="flex flex-col gap-2">
<span class="<?= $message->status ? 'text-blue-500' : 'text-red-500' ?>"><?= $message->message ?></span>
<form onsubmit="validateName">
<input class="border p-2 rounded" type="text" name="name" placeholder="Name" required>
<button class="p-2 bg-blue-500 text-white rounded" type="submit">Submit</button>
</form>
</div>
</div>
Form validation is another common use case for the Validator
class. In this example, we validate a user's name input using the string
method. The function validateName
is called when the form is submitted, and it checks the name input for string length constraints. If the input is invalid, an error message is displayed using the StateManger
class.
Validating Inputs With Rules
- required: This field is required.
- min: This field must be at least $parameter characters long. For example, min:6.
- max: This field must not exceed $parameter characters. For example, max:10.
- startsWith: This field must start with $parameter. For example, startsWith:abc.
- endsWith: This field must end with $parameter. For example, endsWith:def.
- confirmed: The confirmation does not match.
- email: This field must be a valid email address.
- url: This field must be a valid URL.
- ip: This field must be a valid IP address.
- uuid: This field must be a valid UUID.
- cuid: This field must be a valid CUID.
- int: This field must be an integer.
- float: This field must be a float.
- boolean: This field must be a boolean.
- in: The selected value is invalid. For example, in:foo,bar,baz.
- notIn: The selected value is invalid. For example, notIn:foo,bar,baz.
- size: This field must be exactly $parameter characters long. For example, size:6.
- between: This field must be between $min and $max characters long. For example, between:5,10.
- date: This field must be a valid date.
- dateFormat: This field must match the format $parameter. For example, dateFormat:Y-m-d.
- before: This field must be a date before $parameter. For example, before:2022-01-01.
- after: This field must be a date after $parameter. For example, after:2022-01-01.
- json: This field must be a valid JSON string.
- timezone: This field must be a valid timezone.
- regex: This field format is invalid. For example, regex:/^[a-z0-9]+$/.
- digits: This field must be $parameter digits. For example, digits:5.
- digitsBetween: This field must be between $min and $max digits. For example, digitsBetween:5,10.
- extensions: The file must have one of the following extensions: $parameter. For example, extensions:jpg,png,gif.
- mimes: The file must be of type: $mimeTypes. For example, mimes:image/jpg,image/png,image/gif. for more information, see IANA Media Types.
- file: This field must be a valid file.
<?php
use Lib\Validator;
use Lib\StateManager;
$name = StateManager::getState('name');
$password = StateManager::getState('password');
$confirmedPassword = StateManager::getState('confirmedPassword');
function validateInput($data)
{
global $name;
StateManager::setState('name', $data->name);
$validatorValue = Validator::withRules($name, "required|min:10");
echo "validatorValue: ";
var_dump($validatorValue);
echo "<br>";
// Compare the value of $validatorValue to true to check if the validation passed
// If you compare just "if ($validatorValue)", it will pass even if the value returned is a string with an error message
// If you compare "if ($validatorValue === true)", it will pass only if the value is exactly true and not a string
// You can also use "if ($validatorValue !== true)" to check if the value is not exactly true
if ($validatorValue === true) {
echo "Validation passed<br>";
} else {
echo "Validation failed<br>";
}
}
function validateConfirm($data)
{
StateManager::setState('password', $data->password);
StateManager::setState('confirmedPassword', $data->confirmedPassword);
$rules = 'required|confirmed|min:4|max:5';
$validatorValue = Validator::withRules($data->password, $rules, $data->confirmedPassword);
echo "validatorValue: ";
var_dump($validatorValue);
echo "<br>";
// Compare the value of $validatorValue to true to check if the validation passed
// If you compare just "if ($validatorValue)", it will pass even if the value returned is a string with an error message
// If you compare "if ($validatorValue === true)", it will pass only if the value is exactly true and not a string
// You can also use "if ($validatorValue !== true)" to check if the value is not exactly true
if ($validatorValue === true) {
echo "Validation passed<br>";
} else {
echo "Validation failed<br>";
}
}
?>
<form class="max-w-md mx-auto" onsubmit="validateInput">
<div class="mb-4">
<label for="name" class="block text-gray-700 text-sm font-bold mb-2">Name:</label>
<input type="text" name="name" id="name" placeholder="Name" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" value="<?= $name ?>">
</div>
<div class="flex items-center justify-center">
<button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">Submit</button>
</div>
</form>
<form class="max-w-md mx-auto" onsubmit="validateConfirm">
<div class="mb-4">
<label for="password" class="block text-gray-700 text-sm font-bold mb-2">Password:</label>
<input type="text" name="password" id="password" placeholder="password" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" value="<?= $password ?>">
</div>
<div class="mb-4">
<label for="confirmedPassword" class="block text-gray-700 text-sm font-bold mb-2">Confirm Password:</label>
<input type="text" name="confirmedPassword" id="confirmedPassword" placeholder="Confirm Password" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" value="& lt;?= $confirmedPassword ?>">
</div>
<div class="flex items-center justify-center">
<button type="submit" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">Submit</button>
</div>
</form>