UNPKG

@modern-kit/utils

Version:
52 lines (49 loc) 2.01 kB
import { isNumeric } from '../../validator/isNumeric/index.mjs'; const YEAR_SHORT_LENGTH = 6; const YEAR_LONG_LENGTH = 8; const YEAR_2000 = 2e3; const YEAR_1900 = 1900; const parseShortFormatDate = (birthDate) => { const currentYear = (/* @__PURE__ */ new Date()).getFullYear(); const remainingYear = currentYear % 100; const birthYear = Number(birthDate.substring(0, 2)); return { year: remainingYear > birthYear ? YEAR_2000 + birthYear : YEAR_1900 + birthYear, month: Number(birthDate.substring(2, 4)), day: Number(birthDate.substring(4, 6)) }; }; const parseLongFormatDate = (birthDate) => { return { year: Number(birthDate.substring(0, 4)), month: Number(birthDate.substring(4, 6)), day: Number(birthDate.substring(6, 8)) }; }; const isValidDateFormat = (dateString) => { const regex = /^(?:\d{4}|\d{2})[-](?:\d{2})[-](?:\d{2})$|^(?:\d{4}|\d{2})[.](?:\d{2})[.](?:\d{2})$|^(?:\d{4}|\d{2})[\/](?:\d{2})[\/](?:\d{2})$/; return regex.test(dateString); }; const isValidDateInRange = (year, month, day) => { const date = new Date(year, month - 1, day); const currentYear = (/* @__PURE__ */ new Date()).getFullYear(); const isValidYearRange = year >= YEAR_1900 && year <= currentYear; return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day && isValidYearRange; }; function isBirthDate(birthDate) { let birthDateToUse = birthDate; if (isValidDateFormat(birthDateToUse)) { birthDateToUse = birthDateToUse.replace(/[-/.]/g, ""); } if (!isNumeric(birthDateToUse)) { return false; } if (birthDateToUse.length !== YEAR_SHORT_LENGTH && birthDateToUse.length !== YEAR_LONG_LENGTH) { return false; } const parsedBirthDate = birthDateToUse.length === YEAR_SHORT_LENGTH ? parseShortFormatDate(birthDateToUse) : parseLongFormatDate(birthDateToUse); const { year, month, day } = parsedBirthDate; return isValidDateInRange(year, month, day); } export { isBirthDate }; //# sourceMappingURL=index.mjs.map