@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
52 lines (51 loc) • 1.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DEFAULT_DATE_FORMAT = void 0;
exports.splitValue = splitValue;
exports.validateDateOfBirth = validateDateOfBirth;
var _dateFns = require("date-fns");
const DEFAULT_DATE_FORMAT = exports.DEFAULT_DATE_FORMAT = 'yyyy-MM-dd';
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];
}
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 = (0, _dateFns.parseISO)(isoValue);
if (!(0, _dateFns.isValid)(dateValue)) {
return Error(errorDateOfBirth);
}
if ((0, _dateFns.isAfter)(dateValue, new Date())) {
return Error(errorDateOfBirthFuture);
}
}
return undefined;
}
//# sourceMappingURL=validators.js.map