/**
* Validates time values against specified constraints and logs errors.
* @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').
* @param {Object} constraints - An object defining the validation constraints. Example: { min: '08:00', max: '18:00', format: 'HH:mm' }
*/
function validateTimeConstraints(timeData, constraints) {
if (!Array.isArray(timeData)) {
console.error("Error: timeData must be an array.");
return;
}
if (typeof constraints !== 'object' || constraints === null) {
console.error("Error: constraints must be an object.");
return;
}
const { min, max, format } = constraints;
if (min !== undefined && max !== undefined) {
// Check min/max constraints
for (const item of timeData) {
if (item.time === undefined || item.time === null) {
console.error("Error: Time value is missing for an item.");
continue;
}
let timeValue = item.time;
if (typeof timeValue === 'string') {
try {
const date = new Date(timeValue);
if (isNaN(date.getTime())) {
console.error(`Error: Invalid time format for ${timeValue}.`);
continue;
}
timeValue = date; //Convert to Date object
} catch (error) {
console.error(`Error: Could not parse time string ${timeValue}: ${error.message}`);
continue;
}
} else if (!(timeValue instanceof Date)){
console.error(`Error: Time value must be a string or Date object for ${timeValue}`);
continue;
}
const minDate = new Date(`00:00:00`);
const maxDate = new Date(`23:59:59`);
if (timeValue < minDate) {
console.error(`${item.time} is before the minimum time (${min}).`);
} else if (timeValue > maxDate) {
console.error(`${item.time} is after the maximum time (${max}).`);
}
}
}
if (format) {
// Check format constraints
for (const item of timeData) {
if (item.time === undefined || item.time === null) {
console.error("Error: Time value is missing for an item.");
continue;
}
let timeValue = item.time;
if (typeof timeValue === 'string') {
try {
const date = new Date(timeValue);
if (isNaN(date.getTime())) {
console.error(`Error: Invalid time format for ${timeValue}.`);
continue;
}
timeValue = date; //Convert to Date object
} catch (error) {
console.error(`Error: Could not parse time string ${timeValue}: ${error.message}`);
continue;
}
const formattedTime = timeValue.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
if (formattedTime !== format) {
console.error(`Error: Time format ${timeValue} does not match the expected format ${format}.`);
}
}
}
}
}
Add your comment