UNPKG

@dnb/eufemia

Version:

DNB Eufemia Design System UI Library

44 lines 1.71 kB
import { parseISO, isValid, isAfter } from 'date-fns'; export const DEFAULT_DATE_FORMAT = 'yyyy-MM-dd'; export function splitValue(value, dateFormat = DEFAULT_DATE_FORMAT) { if (typeof value !== 'string' || !value) { return [undefined, undefined, undefined]; } const formatPattern = dateFormat.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/yyyy/g, '(\\d{4})').replace(/MM/g, '(\\d{2})').replace(/dd/g, '(\\d{2})'); const regex = new RegExp(`^${formatPattern}$`); const match = value.match(regex); if (!match) { return [undefined, undefined, undefined]; } const yearIndex = dateFormat.indexOf('yyyy'); const monthIndex = dateFormat.indexOf('MM'); const dayIndex = dateFormat.indexOf('dd'); const sortedIndices = [yearIndex, monthIndex, dayIndex].sort((a, b) => a - b); const result = sortedIndices.map((originalIndex, sortedPosition) => { const matchGroupIndex = sortedPosition + 1; return match[matchGroupIndex]; }); const year = result[sortedIndices.indexOf(yearIndex)]; const month = result[sortedIndices.indexOf(monthIndex)]; const day = result[sortedIndices.indexOf(dayIndex)]; return [year, month, day]; } export function validateDateOfBirth(value, { dateFormat = DEFAULT_DATE_FORMAT, errorDateOfBirth, errorDateOfBirthFuture }) { const [year, month, day] = splitValue(value, dateFormat); if (year && month && day) { const isoValue = `${year}-${month}-${day}`; const dateValue = parseISO(isoValue); if (!isValid(dateValue)) { return Error(errorDateOfBirth); } if (isAfter(dateValue, new Date())) { return Error(errorDateOfBirthFuture); } } return undefined; } //# sourceMappingURL=validators.js.map