1. <?php
  2. /**
  3. * Buffers date inputs and provides simple error messages.
  4. *
  5. * @param callable $callback A function to process the validated date. Receives a DateTime object.
  6. * @param array $dateFields An array of field names to validate.
  7. * @return array An array of errors, keyed by field name.
  8. */
  9. function bufferDateInputs(callable $callback, array $dateFields): array
  10. {
  11. $errors = [];
  12. $values = [];
  13. foreach ($dateFields as $field) {
  14. $value = $_POST[$field] ?? $_GET[$field] ?? null; //Get value from POST or GET
  15. $values[$field] = $value;
  16. }
  17. foreach ($dateFields as $field) {
  18. $value = $values[$field] ?? null; // Get the value
  19. if (empty($value)) {
  20. $errors[$field] = "This field is required.";
  21. continue;
  22. }
  23. // Attempt to create a DateTime object. Handles different date formats.
  24. try {
  25. $dateTime = new DateTime($value);
  26. } catch (Exception $e) {
  27. $errors[$field] = "Invalid date format. Please use Y-m-d or Y-m-d H:i:s.";
  28. continue;
  29. }
  30. //Optional validation - Date range check (example)
  31. if ($field === 'birthdate' && $dateTime->format('Y') > date('Y')) {
  32. $errors[$field] = "Birthdate cannot be in the future.";
  33. }
  34. }
  35. if (!empty($errors)) {
  36. return $errors;
  37. } else {
  38. $callback($values); // Call the callback with the validated values
  39. return []; // Return an empty array if no errors
  40. }
  41. }
  42. //Example usage:
  43. /**
  44. * Example function to process the validated date values.
  45. * @param array $dates An array of date values.
  46. */
  47. function processDates(array $dates) {
  48. echo "Birthdate: " . ($dates['birthdate'] ?? 'Not provided') . "<br>";
  49. }
  50. // Example call (replace with your actual form submission or GET request)
  51. // $errors = bufferDateInputs(processDates, ['birthdate', 'start_date']);
  52. // if (empty($errors)) {
  53. // // Process the validated date values
  54. // echo "Dates are valid. Processing...\n";
  55. // } else {
  56. // // Display the errors to the user
  57. // echo "<h2>Validation Errors:</h2>";
  58. // foreach ($errors as $field => $error) {
  59. // echo "- " . $field . ": " . $error . "<br>";
  60. // }
  61. // }
  62. ?>

Add your comment