1. /**
  2. * Validates time values against specified constraints and logs errors.
  3. * @param {Array<Object>} timeData - An array of objects, each with a 'time' property (string or Date object) and optional 'constraint' properties (e.g., 'min', 'max', 'format').
  4. * @param {Object} constraints - An object defining the validation constraints. Example: { min: '08:00', max: '18:00', format: 'HH:mm' }
  5. */
  6. function validateTimeConstraints(timeData, constraints) {
  7. if (!Array.isArray(timeData)) {
  8. console.error("Error: timeData must be an array.");
  9. return;
  10. }
  11. if (typeof constraints !== 'object' || constraints === null) {
  12. console.error("Error: constraints must be an object.");
  13. return;
  14. }
  15. const { min, max, format } = constraints;
  16. if (min !== undefined && max !== undefined) {
  17. // Check min/max constraints
  18. for (const item of timeData) {
  19. if (item.time === undefined || item.time === null) {
  20. console.error("Error: Time value is missing for an item.");
  21. continue;
  22. }
  23. let timeValue = item.time;
  24. if (typeof timeValue === 'string') {
  25. try {
  26. const date = new Date(timeValue);
  27. if (isNaN(date.getTime())) {
  28. console.error(`Error: Invalid time format for ${timeValue}.`);
  29. continue;
  30. }
  31. timeValue = date; //Convert to Date object
  32. } catch (error) {
  33. console.error(`Error: Could not parse time string ${timeValue}: ${error.message}`);
  34. continue;
  35. }
  36. } else if (!(timeValue instanceof Date)){
  37. console.error(`Error: Time value must be a string or Date object for ${timeValue}`);
  38. continue;
  39. }
  40. const minDate = new Date(`00:00:00`);
  41. const maxDate = new Date(`23:59:59`);
  42. if (timeValue < minDate) {
  43. console.error(`${item.time} is before the minimum time (${min}).`);
  44. } else if (timeValue > maxDate) {
  45. console.error(`${item.time} is after the maximum time (${max}).`);
  46. }
  47. }
  48. }
  49. if (format) {
  50. // Check format constraints
  51. for (const item of timeData) {
  52. if (item.time === undefined || item.time === null) {
  53. console.error("Error: Time value is missing for an item.");
  54. continue;
  55. }
  56. let timeValue = item.time;
  57. if (typeof timeValue === 'string') {
  58. try {
  59. const date = new Date(timeValue);
  60. if (isNaN(date.getTime())) {
  61. console.error(`Error: Invalid time format for ${timeValue}.`);
  62. continue;
  63. }
  64. timeValue = date; //Convert to Date object
  65. } catch (error) {
  66. console.error(`Error: Could not parse time string ${timeValue}: ${error.message}`);
  67. continue;
  68. }
  69. const formattedTime = timeValue.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  70. if (formattedTime !== format) {
  71. console.error(`Error: Time format ${timeValue} does not match the expected format ${format}.`);
  72. }
  73. }
  74. }
  75. }
  76. }

Add your comment