| 47 | * @returns {object} { isValid: boolean, error?: string, errorType?: string, errorName?: string } |
| 48 | */ |
| 49 | export const validateDateComponents = (dateString) => { |
| 50 | // Regex para extrair ano, mês e dia de uma data no formato YYYY-MM-DD |
| 51 | const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/; |
| 52 | const match = dateString.match(dateRegex); |
| 53 | |
| 54 | if (!match) { |
| 55 | return { |
| 56 | isValid: false, |
| 57 | error: 'Formato de data inválida, utilize: YYYY-MM-DD', |
| 58 | errorType: 'format_error', |
| 59 | errorName: 'DATE_FORMAT_INCORRECT_PATTERN', |
| 60 | }; |
| 61 | } |
| 62 | |
| 63 | const year = parseInt(match[1], 10); |
| 64 | const month = parseInt(match[2], 10); |
| 65 | const day = parseInt(match[3], 10); |
| 66 | |
| 67 | // Validar mês (01-12) |
| 68 | if (month < 1 || month > 12) { |
| 69 | return { |
| 70 | isValid: false, |
| 71 | error: 'Mês inválido: deve estar entre 01 e 12', |
| 72 | errorType: 'format_error', |
| 73 | errorName: 'INVALID_MONTH_VALUE', |
| 74 | }; |
| 75 | } |
| 76 | |
| 77 | // Validar dia (01-31 considerando o mês específico) |
| 78 | const daysInMonth = dayjs( |
| 79 | `${year}-${month.toString().padStart(2, '0')}-01` |
| 80 | ).daysInMonth(); |
| 81 | |
| 82 | if (day < 1 || day > daysInMonth) { |
| 83 | return { |
| 84 | isValid: false, |
| 85 | error: `Dia inválido: deve estar entre 01 e ${daysInMonth} para o mês ${month |
| 86 | .toString() |
| 87 | .padStart(2, '0')}`, |
| 88 | errorType: 'format_error', |
| 89 | errorName: 'INVALID_DAY_VALUE', |
| 90 | }; |
| 91 | } |
| 92 | |
| 93 | // Validar que a data final corresponde aos componentes fornecidos |
| 94 | // Isso garante que dayjs não fez ajustes silenciosos |
| 95 | const parsedDate = dayjs(dateString, 'YYYY-MM-DD', true); // strict mode |
| 96 | |
| 97 | if (!parsedDate.isValid()) { |
| 98 | return { |
| 99 | isValid: false, |
| 100 | error: 'Data inválida', |
| 101 | errorType: 'format_error', |
| 102 | errorName: 'INVALID_DATE', |
| 103 | }; |
| 104 | } |
| 105 | |
| 106 | // Verificar se os componentes da data parseada correspondem aos fornecidos |