<?php
/**
* Buffers date inputs and provides simple error messages.
*
* @param callable $callback A function to process the validated date. Receives a DateTime object.
* @param array $dateFields An array of field names to validate.
* @return array An array of errors, keyed by field name.
*/
function bufferDateInputs(callable $callback, array $dateFields): array
{
$errors = [];
$values = [];
foreach ($dateFields as $field) {
$value = $_POST[$field] ?? $_GET[$field] ?? null; //Get value from POST or GET
$values[$field] = $value;
}
foreach ($dateFields as $field) {
$value = $values[$field] ?? null; // Get the value
if (empty($value)) {
$errors[$field] = "This field is required.";
continue;
}
// Attempt to create a DateTime object. Handles different date formats.
try {
$dateTime = new DateTime($value);
} catch (Exception $e) {
$errors[$field] = "Invalid date format. Please use Y-m-d or Y-m-d H:i:s.";
continue;
}
//Optional validation - Date range check (example)
if ($field === 'birthdate' && $dateTime->format('Y') > date('Y')) {
$errors[$field] = "Birthdate cannot be in the future.";
}
}
if (!empty($errors)) {
return $errors;
} else {
$callback($values); // Call the callback with the validated values
return []; // Return an empty array if no errors
}
}
//Example usage:
/**
* Example function to process the validated date values.
* @param array $dates An array of date values.
*/
function processDates(array $dates) {
echo "Birthdate: " . ($dates['birthdate'] ?? 'Not provided') . "<br>";
}
// Example call (replace with your actual form submission or GET request)
// $errors = bufferDateInputs(processDates, ['birthdate', 'start_date']);
// if (empty($errors)) {
// // Process the validated date values
// echo "Dates are valid. Processing...\n";
// } else {
// // Display the errors to the user
// echo "<h2>Validation Errors:</h2>";
// foreach ($errors as $field => $error) {
// echo "- " . $field . ": " . $error . "<br>";
// }
// }
?>
Add your comment