@widergy/web-utils
Version:
Utility GO! Web utils
587 lines (586 loc) • 34.7 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fileSignatureValidation = exports.documentValidation = exports.validateRut = exports.validateDocumentNumber = exports.validateAnimatedCreditCard = exports.validateSketch = exports.validatePhoneWithChildKeys = exports.validateCreditCard = exports.validateInvalidBins = exports.validateRequiredOnField = exports.validateDependantField = exports.passwordValidations = exports.logicValidation = exports.genKeyMap = exports.notEqual = exports.letterAndNumberRequired = exports.minYear = exports.minNum = exports.maxNum = exports.dateIsInRange = exports.minDate = exports.maxDate = exports.cuitFormat = exports.atLeastOneUpperCase = exports.atLeastOneLowerCase = exports.atLeastOneNumber = exports.lettersAndSpaces = exports.numericalTenDigits = exports.numericalFourDigits = exports.url = exports.email = exports.pattern = exports.phoneLength = exports.cuitValidate = exports.lengthEquals = exports.validateCBU = exports.compareCBUDigits = exports.getLastDigit = exports.validateEquals = exports.maxLength = exports.validateMaxLength = exports.attachmentMinLength = exports.minLength = exports.validateMinLength = exports.required = exports.meetCuitRequirements = exports.validDate = exports.checkCustomDateValidations = exports.validDateCreditCard = exports.regexValidations = void 0;
exports.validateBetweenValues = exports.validateOnlyLettersAndNumbers = exports.differentValue = exports.sameValue = exports.fileSizeValidation = void 0;
const dayjs_1 = __importDefault(require("dayjs"));
const isSameOrAfter_1 = __importDefault(require("dayjs/plugin/isSameOrAfter"));
const isSameOrBefore_1 = __importDefault(require("dayjs/plugin/isSameOrBefore"));
const customParseFormat_1 = __importDefault(require("dayjs/plugin/customParseFormat"));
const payment_1 = __importDefault(require("payment"));
const expr_eval_1 = require("expr-eval");
const seamless_immutable_1 = require("seamless-immutable");
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
const regularExpressions_1 = require("./constants/regularExpressions");
const files_1 = require("./constants/files");
const cbuField_1 = require("./constants/cbuField");
const normalize_1 = require("./normalize");
const creditCard_1 = require("./creditCard");
const defaultMessages_1 = require("./constants/defaultMessages");
const object_1 = require("./object");
const number_1 = require("./number");
const creditCards_1 = require("./constants/creditCards");
dayjs_1.default.extend(isSameOrBefore_1.default);
dayjs_1.default.extend(isSameOrAfter_1.default);
dayjs_1.default.extend(customParseFormat_1.default);
const validateLetterAndNumberRequired = (str) => {
if (str.search(/\d/) === -1) {
return false;
}
if (str.search(/[a-zA-ZñÑ]/) === -1) {
return false;
}
if (!(str.search(/[+`ç´*]/) === -1)) {
return false;
}
return true;
};
const regexValidations = (regExps) => (value = '') => { var _a; return (_a = regExps.find(({ expression }) => !new RegExp(expression).test(value))) === null || _a === void 0 ? void 0 : _a.error; };
exports.regexValidations = regexValidations;
const validDateCreditCard = (errorMessage) => (val) => (0, dayjs_1.default)(val, 'MM/YY', true).isValid() ? undefined : errorMessage;
exports.validDateCreditCard = validDateCreditCard;
const convertTZ = (date, tzString) => new Date((typeof date === 'string' ? new Date(date) : date).toLocaleString('en-US', { timeZone: tzString }));
const getPastMonthDates = (onlyPastMonth = false) => {
if (!onlyPastMonth)
return {};
const date = new Date();
const currentYear = date.getFullYear();
const currentMonth = date.getMonth();
return {
minDate: new Date(currentYear, currentMonth - 1, 1),
maxDate: new Date(currentYear, currentMonth, 0),
};
};
const checkCustomDateValidations = (dateValidations, format) => (val, allValues) => {
var _a, _b, _c, _d, _e, _f, _g, _h, _j;
if (!val)
return undefined;
let possibleFormats = ['DD/MM/YYYY'];
if (format)
possibleFormats.push(format);
const dateValue = (0, dayjs_1.default)(val, possibleFormats, true);
if (dateValue.isValid()) {
const currentDate = (dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.timeZone)
? (0, dayjs_1.default)(convertTZ(new Date(), dateValidations.timeZone))
: (0, dayjs_1.default)();
if ((_a = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidSameOrBeforeDates) === null || _a === void 0 ? void 0 : _a.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidSameOrBeforeDates;
if (currentDate.isSame(dateValue, 'day') || currentDate.isAfter(dateValue, 'day'))
return config.errorMessage;
}
if ((_b = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidDaysAfter) === null || _b === void 0 ? void 0 : _b.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidDaysAfter;
if (dateValue.isSameOrBefore(currentDate.add(config.days, 'day'), 'day'))
return config.errorMessage;
}
if ((_c = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.checkMaxHourThreshold) === null || _c === void 0 ? void 0 : _c.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.checkMaxHourThreshold;
if ((config === null || config === void 0 ? void 0 : config.hour) && (dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.timeZone)) {
const isThresholdHour = currentDate.hour() >= parseInt(config.hour, 10);
const selectedDateIsTomorrow = currentDate.add(1, 'day').isSame(dateValue, 'day');
if (isThresholdHour && selectedDateIsTomorrow)
return config.errorMessage;
}
}
if ((_d = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidWeekends) === null || _d === void 0 ? void 0 : _d.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidWeekends;
if (config.weekendDays.some((day) => day === dateValue.day()))
return config.errorMessage;
}
if ((_e = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidHolidays) === null || _e === void 0 ? void 0 : _e.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidHolidays;
if (config.holidays.some((invalidDate) => (0, dayjs_1.default)(invalidDate, 'DD/MM/YYYY', true).isSame(dateValue, 'day')))
return config.errorMessage;
}
if ((_f = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidAfterPlusDays) === null || _f === void 0 ? void 0 : _f.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidAfterPlusDays;
if (dateValue.isAfter(currentDate.add(config.days, 'day')))
return config.errorMessage;
}
if ((_g = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidWeekDaysWithValidation) === null || _g === void 0 ? void 0 : _g.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidWeekDaysWithValidation;
if (config.validate_field_id && config.validate_field_values) {
const validateFieldValue = allValues[config.validate_field_id];
if (validateFieldValue) {
const fieldConfig = config.validate_field_values[validateFieldValue];
if (fieldConfig && fieldConfig.days.some((day) => day === dateValue.day()))
return fieldConfig.errorMessage;
}
}
}
if ((_h = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.onlyPastMonth) === null || _h === void 0 ? void 0 : _h.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.onlyPastMonth;
const pastMonthDates = getPastMonthDates(config.active);
const { minDate, maxDate } = pastMonthDates;
if (dateValue.isBefore((0, dayjs_1.default)(minDate)) || dateValue.isAfter((0, dayjs_1.default)(maxDate)))
return config.errorMessage;
}
if ((_j = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidFutureDates) === null || _j === void 0 ? void 0 : _j.active) {
const config = dateValidations === null || dateValidations === void 0 ? void 0 : dateValidations.avoidFutureDates;
if (dateValue.isAfter(currentDate))
return config.errorMessage;
}
}
return undefined;
};
exports.checkCustomDateValidations = checkCustomDateValidations;
const validDate = (errorMessage) => (val) => val && !(0, dayjs_1.default)(val, 'DD/MM/YYYY', true).isValid() ? errorMessage : undefined;
exports.validDate = validDate;
const meetCuitRequirements = (cuit) => {
const digits = (0, normalize_1.onlyNumbers)(cuit);
const splittedDigits = digits.split('');
const lastDigit = parseInt(splittedDigits.pop() || '', 10);
let accum = 0;
for (let i = 0; i < splittedDigits.length; i += 1) {
accum += parseInt(splittedDigits[9 - i], 10) * (2 + (i % 6));
}
let requiredDigit = 11 - (accum % 11);
if (requiredDigit === 11)
requiredDigit = 0;
return lastDigit === requiredDigit;
};
exports.meetCuitRequirements = meetCuitRequirements;
const required = (errorMessage) => (val) => {
if (!val)
return errorMessage;
if (typeof val === 'object' && (0, object_1.objectIsEmpty)(val))
return errorMessage;
if (Array.isArray(val) && (0, isEmpty_1.default)(val))
return errorMessage;
return undefined;
};
exports.required = required;
const validateMinLength = (val, min) => val && val.length >= min;
exports.validateMinLength = validateMinLength;
const minLength = (min, errorMessage) => (val) => val && !(0, exports.validateMinLength)(val, min) ? errorMessage : undefined;
exports.minLength = minLength;
const attachmentMinLength = (min, errorMessage) => (val) => val && (val === null || val === void 0 ? void 0 : val.files) && !(0, exports.validateMinLength)(val.files, min) ? errorMessage : undefined;
exports.attachmentMinLength = attachmentMinLength;
const validateMaxLength = (val, max) => val && val.length <= max;
exports.validateMaxLength = validateMaxLength;
const maxLength = (max, errorMessage) => (val) => val && !(0, exports.validateMaxLength)(val, max) ? errorMessage : undefined;
exports.maxLength = maxLength;
const validateEquals = (val, length) => val && val.length === length;
exports.validateEquals = validateEquals;
const getLastDigit = (val = []) => parseInt(val.toString().split('').pop(), 10);
exports.getLastDigit = getLastDigit;
const compareCBUDigits = (valueToCompare, cbuDigitToCompare) => (10 - valueToCompare) % 10 === parseInt(cbuDigitToCompare, 10);
exports.compareCBUDigits = compareCBUDigits;
const validateCBUDigits = (cbuDigits = [], multipliers = [], start = 0, end = 0) => {
const extractedDigits = cbuDigits.slice(start, end);
const valueToCompare = extractedDigits.reduce((acc, curr, i) => acc + curr * multipliers[i], 0);
return (0, exports.compareCBUDigits)((0, exports.getLastDigit)(valueToCompare), cbuDigits[end]);
};
const validateCBU = (cbuEntityKey, cbuNumberKey, errorMessage, invalidFormatErrorMessage) => (value = {}) => {
const cbuDigits = value[cbuNumberKey].split('');
return (0, exports.validateEquals)(value[cbuNumberKey], 22)
? value[cbuEntityKey] &&
validateCBUDigits(cbuDigits, cbuField_1.firstBlockNumbersToMultiply, 0, 7) &&
validateCBUDigits(cbuDigits, cbuField_1.secondBlockNumbersToMultiply, 8, 21)
? undefined
: errorMessage
: invalidFormatErrorMessage;
};
exports.validateCBU = validateCBU;
const lengthEquals = (length, errorMessage, onlyNumbers) => (val) => val && !(0, exports.validateEquals)(onlyNumbers ? (0, normalize_1.onlyNumbers)(val) : val, length) ? errorMessage : undefined;
exports.lengthEquals = lengthEquals;
const cuitValidate = (string, errorMessage) => (val) => val && val[0] !== string ? errorMessage : undefined;
exports.cuitValidate = cuitValidate;
const phoneLength = (length, errorMessage) => (val) => {
const value = val && val.replace(/[-]/, '');
return value && value.length !== length ? errorMessage : undefined;
};
exports.phoneLength = phoneLength;
const pattern = (exp, errorMessage) => (val) => val && !exp.test(val) ? errorMessage : undefined;
exports.pattern = pattern;
const email = (errorMessage) => (0, exports.pattern)(regularExpressions_1.emailRegex, errorMessage);
exports.email = email;
const url = (errorMessage) => (0, exports.pattern)(regularExpressions_1.urlRegex, errorMessage);
exports.url = url;
const numericalFourDigits = (errorMessage) => (0, exports.pattern)(regularExpressions_1.numericalFourDigitsRegex, errorMessage);
exports.numericalFourDigits = numericalFourDigits;
const numericalTenDigits = (errorMessage) => (0, exports.pattern)(regularExpressions_1.numericalTenDigitsRegex, errorMessage);
exports.numericalTenDigits = numericalTenDigits;
const lettersAndSpaces = (errorMessage) => (0, exports.pattern)(regularExpressions_1.lettersAndSpacesRegex, errorMessage);
exports.lettersAndSpaces = lettersAndSpaces;
const atLeastOneNumber = (errorMessage) => (0, exports.pattern)(regularExpressions_1.atLeastOneNumberRegex, errorMessage);
exports.atLeastOneNumber = atLeastOneNumber;
const atLeastOneLowerCase = (errorMessage) => (0, exports.pattern)(regularExpressions_1.atLeastOneLowerCaseRegex, errorMessage);
exports.atLeastOneLowerCase = atLeastOneLowerCase;
const atLeastOneUpperCase = (errorMessage) => (0, exports.pattern)(regularExpressions_1.atLeastOneUpperCaseRegex, errorMessage);
exports.atLeastOneUpperCase = atLeastOneUpperCase;
const cuitFormat = (errorMessage) => (val) => (0, exports.validateMinLength)(val, 11) && (0, exports.meetCuitRequirements)(val) ? undefined : errorMessage;
exports.cuitFormat = cuitFormat;
const maxDate = (maxDate, errorMessage) => (val) => {
if (!val)
return;
const dateToValidate = (0, dayjs_1.default)(val, 'DD/MM/YYYY').format('YYYY-MM-DD');
return (0, dayjs_1.default)(dateToValidate).isSameOrBefore((0, dayjs_1.default)(maxDate, 'DD/MM/YYYY').format('YYYY-MM-DD'))
? undefined
: errorMessage;
};
exports.maxDate = maxDate;
const minDate = (minDate, errorMessage) => (val) => {
if (!val)
return;
const dateToValidate = (0, dayjs_1.default)(val, 'DD/MM/YYYY').format('YYYY-MM-DD');
return (0, dayjs_1.default)(dateToValidate).isSameOrAfter((0, dayjs_1.default)(minDate, 'DD/MM/YYYY').format('YYYY-MM-DD'))
? undefined
: errorMessage;
};
exports.minDate = minDate;
const dateIsInRange = (lowBound, topBound, errorMessage) => (val) => {
return (0, exports.minDate)(lowBound, errorMessage)(val) || (0, exports.maxDate)(topBound, errorMessage)(val);
};
exports.dateIsInRange = dateIsInRange;
const maxNum = (max, errorMessage) => (value) => value && !(value <= max) ? errorMessage : undefined;
exports.maxNum = maxNum;
const minNum = (min, errorMessage) => (value) => value && min >= value ? errorMessage : undefined;
exports.minNum = minNum;
const minYear = (year, errorMessage) => (value) => value && !(value >= year) ? errorMessage : undefined;
exports.minYear = minYear;
const letterAndNumberRequired = (errorMessage) => (val) => validateLetterAndNumberRequired(val) ? undefined : errorMessage;
exports.letterAndNumberRequired = letterAndNumberRequired;
const notEqual = (compareValue, errorMessage) => (value) => compareValue === value ? errorMessage : undefined;
exports.notEqual = notEqual;
const genKeyMap = (fields, idOrKey) => {
const keyMap = {};
fields.forEach((field) => {
const index = `${field.key}_${field.order}`;
keyMap[index] = `${idOrKey}${field.id}`;
});
return keyMap;
};
exports.genKeyMap = genKeyMap;
const replaceKeys = (map) => (str) => str.replace(/\$([a-zA-Z\d-_\.]+_\d+)\b/g, ({}, key) => map[key]);
const keyToValue = (expr, allValues, idOrKey) => expr.replace(idOrKey === 'id' ? /id\d+\b/g : /key\d+\b/g, (match) => allValues[match]);
const logicValidation = (keyMap, logicEvaluation, errorMessage, idOrKey) => (_, allValues) => {
const expression = replaceKeys(keyMap)(logicEvaluation);
try {
const expr = keyToValue(expression, allValues, idOrKey);
return expr_eval_1.Parser.evaluate(expr) ? undefined : errorMessage;
}
catch (err) {
return undefined;
}
};
exports.logicValidation = logicValidation;
const validatePasswordStrength = (errorMessage, regexs = regularExpressions_1.passwordWithMultipleGroups, minRequiredValidations = 3) => (value) => regexs.map((regex) => (regex.test(value) ? 1 : 0)).reduce((a, b) => a + b, 0) >=
minRequiredValidations
? undefined
: errorMessage;
const passwordValidations = (passMinLength, passMaxLength, requireNumberLetter, requireMultipleGroups, errorMessages, regexs, minRequiredValidations) => {
const validate = [(0, exports.required)((0, seamless_immutable_1.getIn)(errorMessages, ['passwordRequired'], defaultMessages_1.DefaultMessages.passwordRequired))];
if (passMinLength === passMaxLength) {
validate.push((0, exports.lengthEquals)(passMinLength, (0, seamless_immutable_1.getIn)(errorMessages, ['passwordExactLength'], defaultMessages_1.DefaultMessages.passwordExactLength)));
}
else {
validate.push((0, exports.minLength)(passMinLength, (0, seamless_immutable_1.getIn)(errorMessages, ['passwordMinLength'], defaultMessages_1.DefaultMessages.passwordMinLength)));
validate.push((0, exports.maxLength)(passMaxLength, (0, seamless_immutable_1.getIn)(errorMessages, ['passwordMaxLength'], defaultMessages_1.DefaultMessages.passwordMaxLength)));
}
if (requireNumberLetter)
validate.push((0, exports.letterAndNumberRequired)((0, seamless_immutable_1.getIn)(errorMessages, ['passwordRequireLetterAndNumber'], defaultMessages_1.DefaultMessages.passwordRequireLetterAndNumber)));
if (requireMultipleGroups)
validate.push(validatePasswordStrength((0, seamless_immutable_1.getIn)(errorMessages, ['passwordStrength'], defaultMessages_1.DefaultMessages.passwordStrength), regexs, minRequiredValidations));
return validate;
};
exports.passwordValidations = passwordValidations;
const validateDependantField = (dependantFieldName, errorMessage) => (val, allValues) => val || allValues[dependantFieldName] ? undefined : errorMessage;
exports.validateDependantField = validateDependantField;
const validateRequiredOnField = (requiredOnFieldName, errorMessage) => (val, allValues) => allValues[requiredOnFieldName] && !val ? errorMessage : undefined;
exports.validateRequiredOnField = validateRequiredOnField;
const validateInvalidBins = (invalidBins, errorMessage) => (value) => {
const bin = value && value.substring(0, 6);
return invalidBins.includes(bin) && errorMessage;
};
exports.validateInvalidBins = validateInvalidBins;
const validateCreditCard = (errorMessage) => (value) => {
const payment = payment_1.default;
(0, creditCard_1.fixCreditCardsPatterns)(payment);
const issuer = payment.fns.cardType(value);
const isValid = issuer === creditCards_1.cards.NARANJA || payment.fns.validateCardNumber(value);
return !isValid && errorMessage;
};
exports.validateCreditCard = validateCreditCard;
const validatePhoneWithChildKeys = (errorMessage) => (value) => {
if (value) {
const valuesArray = Object.values(value);
return (0, isEmpty_1.default)(valuesArray) ||
!valuesArray[0] ||
!valuesArray[1] ||
`${valuesArray[0]}${valuesArray[1]}`.length !== 10
? errorMessage
: undefined;
}
return undefined;
};
exports.validatePhoneWithChildKeys = validatePhoneWithChildKeys;
const validateSketch = (errorMessages, configuration) => (value = {}) => {
const messages = {};
const childKeys = configuration.child_keys || {};
const optionalKeys = ['leftNeighbor', 'rightNeighbor'];
Object.keys(childKeys).forEach((key) => {
const currentKey = childKeys[key];
if (!optionalKeys.includes(key) && (0, isEmpty_1.default)(value[currentKey])) {
messages[currentKey] = (0, seamless_immutable_1.getIn)(errorMessages, [key], defaultMessages_1.DefaultMessages.sketchRequired);
}
});
const validations = JSON.stringify(messages);
return Object.keys(messages).length > 0 && validations;
};
exports.validateSketch = validateSketch;
const validateAnimatedCreditCard = (errorMessages, childKeys, invalidBins) => (value = {}) => {
const messages = {};
const [cardNumberKey, holderNameKey, securityCodeKey, expMonthKey, expYearKey] = childKeys;
const expires = value[expYearKey] && value[expMonthKey] && `${value[expYearKey]}${value[expMonthKey]}`;
if (!value[cardNumberKey] || value[cardNumberKey].length === 0) {
messages.cardNumber = (0, seamless_immutable_1.getIn)(errorMessages, ['cardNumberRequired'], defaultMessages_1.DefaultMessages.cardNumberRequired);
}
else {
const payment = payment_1.default;
(0, creditCard_1.fixCreditCardsPatterns)(payment);
const issuer = payment.fns.cardType(value[cardNumberKey]);
const isValid = issuer === creditCards_1.cards.MAESTRO || payment.fns.validateCardNumber(value[cardNumberKey]);
if (!isValid)
messages.cardNumber = (0, seamless_immutable_1.getIn)(errorMessages, ['invalidCardNumber'], defaultMessages_1.DefaultMessages.invalidCardNumber);
}
if (invalidBins) {
const errorMessage = (0, seamless_immutable_1.getIn)(errorMessages, ['disabledCardNumber'], defaultMessages_1.DefaultMessages.invalidCardNumber);
const isInvalid = (0, exports.validateInvalidBins)(invalidBins, errorMessage)(value[cardNumberKey]);
if (isInvalid) {
messages.cardNumber = errorMessage;
}
}
if (!value[holderNameKey] || value[holderNameKey].length === 0)
messages.holderName = (0, seamless_immutable_1.getIn)(errorMessages, ['holderNameRequired'], defaultMessages_1.DefaultMessages.holderNameRequired);
if (!value[expMonthKey] ||
!value[expYearKey] ||
value[expMonthKey].length === 0 ||
value[expYearKey].length === 0) {
messages.expires = (0, seamless_immutable_1.getIn)(errorMessages, ['expiresRequired'], defaultMessages_1.DefaultMessages.expiresRequired);
}
else {
const creditCardDate = (0, dayjs_1.default)(expires, 'YYYYMM', true);
const today = (0, dayjs_1.default)();
const isValidDate = creditCardDate.isValid() && today < creditCardDate.add(1, 'months') && expires.length === 6;
if (!isValidDate)
messages.expires = (0, seamless_immutable_1.getIn)(errorMessages, ['invalidExpires'], defaultMessages_1.DefaultMessages.invalidExpires);
}
if (!value[securityCodeKey] || value[securityCodeKey].length === 0)
messages.securityCode = (0, seamless_immutable_1.getIn)(errorMessages, ['securityCodeRequired'], defaultMessages_1.DefaultMessages.securityCodeRequired);
const validations = JSON.stringify(messages);
return Object.keys(messages).length > 0 && validations;
};
exports.validateAnimatedCreditCard = validateAnimatedCreditCard;
const validateNoInitialZero = (value) => value && value.substring(0, 1) !== '0';
const validateDocumentNumber = (errorMessage) => (value) => !(0, exports.validateMinLength)(value, 6)
? errorMessage
: !(0, exports.validateMaxLength)(value, 8)
? errorMessage
: !validateNoInitialZero(value)
? errorMessage
: undefined;
exports.validateDocumentNumber = validateDocumentNumber;
const checkSignature = (fileSignature, admitedTypes, fileType) => {
if (fileSignature && fileType && fileType.length > 1) {
const fieldTypeName = admitedTypes.find((admitedType) => files_1.inputFiles[admitedType].validType.includes(fileType));
return fieldTypeName && ((0, isEmpty_1.default)(files_1.inputFiles[fieldTypeName].signatures) || files_1.inputFiles[fieldTypeName].signatures.includes(fileSignature.toUpperCase()));
}
return false;
};
const documentValidationDefaultMessages = {
dni: 'El DNI ingresado no tiene un formato válido',
dne: 'El DNE ingresado no tiene un formato válido',
dnr: 'El DNR ingresado no tiene un formato válido',
cuit: 'El CUIT ingresado no tiene un formato válido',
other: 'El número de documento ingresado no tiene un formato válido',
['provincial_ci']: 'El CI Provincial ingresado no tiene un formato válido',
['identity_card']: 'La Cédula de identidad ingresada no tiene un formato válido',
['enlistment_book']: 'La Libreta de enrolamiento ingresada no tiene un formato válido',
passport: 'El Pasaporte ingresado no tiene un formato válido',
['civic_notebook']: 'La Libreta cívica ingresada no tiene un formato válido',
rut: 'El RUT ingresado no tiene un formato válido',
default: 'El documento ingresado no tiene un formato válido',
};
const dv = (value) => {
let multiplier = 0;
let sum = 0;
let i = 0;
while (value > 0) {
multiplier = (i % 6) + 2;
const digit = value % 10;
sum += digit * multiplier;
value = Math.floor(value / 10);
i++;
}
const remainder = 11 - (sum % 11);
return remainder === 10 ? 'k' : remainder % 11;
};
const validateRut = (value) => {
if (!/^[0-9]+-[0-9kK]{1}$/.test(value))
return false;
const tmp = value.split('-');
let digv = tmp[1];
const rut = parseInt(tmp[0], 10);
if (digv == 'K')
digv = 'k';
return dv(rut) == digv;
};
exports.validateRut = validateRut;
const documentValidation = (messages, docTypeId, docTypeKey, docTypeMapping) => (value, allValues) => {
let type = allValues[docTypeKey] || allValues.docType || allValues.document_type || allValues[`id${docTypeId}`];
type = (docTypeMapping === null || docTypeMapping === void 0 ? void 0 : docTypeMapping[type]) || type;
switch (type) {
case 'dni':
return (0, exports.validateMinLength)(value, 6) && (0, exports.validateMaxLength)(value, 8)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'dne':
return (0, exports.validateMinLength)(value, 6) && (0, exports.validateMaxLength)(value, 8)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'dnr':
return (0, exports.validateMinLength)(value, 6) && (0, exports.validateMaxLength)(value, 8)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'cuit':
return (0, exports.validateEquals)(value, 11) && (0, exports.meetCuitRequirements)(value)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'other':
return (0, exports.validateMinLength)(value, 5) && (0, exports.validateMaxLength)(value, 11)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'provincial_ci':
return (0, exports.validateMinLength)(value, 7) && (0, exports.validateMaxLength)(value, 8)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'identity_card':
return (0, exports.validateMinLength)(value, 7) && (0, exports.validateMaxLength)(value, 8)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'enlistment_book':
return (0, exports.validateMinLength)(value, 6) && (0, exports.validateMaxLength)(value, 8)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'cert_of_document_in_proccess':
return (0, exports.validateMinLength)(value, 5) && (0, exports.validateMaxLength)(value, 11)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'passport':
return (0, exports.validateMinLength)(value, 7) && (0, exports.validateMaxLength)(value, 9)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'civic_notebook':
return (0, exports.validateMinLength)(value, 6) && (0, exports.validateMaxLength)(value, 8)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
case 'rut':
return (0, exports.validateRut)(value)
? undefined
: (messages && messages[type]) || documentValidationDefaultMessages[type];
default:
return value
? undefined
: (messages && messages.default) || documentValidationDefaultMessages.default;
}
};
exports.documentValidation = documentValidation;
function readFileAsync(file, admitedTypes, fileType) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
let fileSignature = '';
const bytes = new Uint8Array(e.target.result);
for (let i = 0; i < bytes.length; i += 1) {
const byte = bytes[i];
fileSignature += (byte < 10 ? '0' : '') + byte.toString(16);
}
const result = checkSignature(fileSignature, admitedTypes, fileType);
resolve(result);
};
reader.onerror = reject;
reader.readAsArrayBuffer(file.slice(0, 4));
});
}
const fileSignatureValidation = async (file, admitedTypes, fileType) => {
const result = await readFileAsync(file, admitedTypes, fileType);
return !!result;
};
exports.fileSignatureValidation = fileSignatureValidation;
const fileSizeValidation = (file, maxFileSize) => {
return file.size <= maxFileSize;
};
exports.fileSizeValidation = fileSizeValidation;
const sameValue = (key, errorMessage) => (value, allValues) => value === allValues[key] ? undefined : errorMessage;
exports.sameValue = sameValue;
const differentValue = (key, errorMessage) => (value, allValues) => value && allValues[key] && value !== allValues[key] ? undefined : errorMessage;
exports.differentValue = differentValue;
const validateOnlyLettersAndNumbers = (errorMessage) => (value) => /[^a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ ]/g.test(value) ? errorMessage : undefined;
exports.validateOnlyLettersAndNumbers = validateOnlyLettersAndNumbers;
const validateBetweenValues = (min, max, errorMessage, hasSign) => (val) => {
let value = val;
if (hasSign)
value = val.substring(1);
return (0, number_1.between)(min, max, parseInt(value, 10)) ? undefined : errorMessage;
};
exports.validateBetweenValues = validateBetweenValues;
const VALIDATE_UTILS = {
regexValidations: exports.regexValidations,
atLeastOneNumber: exports.atLeastOneNumber,
atLeastOneLowerCase: exports.atLeastOneLowerCase,
atLeastOneUpperCase: exports.atLeastOneUpperCase,
validDateCreditCard: exports.validDateCreditCard,
validDate: exports.validDate,
meetCuitRequirements: exports.meetCuitRequirements,
required: exports.required,
validateMinLength: exports.validateMinLength,
minLength: exports.minLength,
attachmentMinLength: exports.attachmentMinLength,
validateMaxLength: exports.validateMaxLength,
maxLength: exports.maxLength,
validateEquals: exports.validateEquals,
lengthEquals: exports.lengthEquals,
cuitValidate: exports.cuitValidate,
logicValidation: exports.logicValidation,
genKeyMap: exports.genKeyMap,
phoneLength: exports.phoneLength,
pattern: exports.pattern,
email: exports.email,
url: exports.url,
numericalFourDigits: exports.numericalFourDigits,
numericalTenDigits: exports.numericalTenDigits,
lettersAndSpaces: exports.lettersAndSpaces,
cuitFormat: exports.cuitFormat,
maxDate: exports.maxDate,
minDate: exports.minDate,
dateIsInRange: exports.dateIsInRange,
maxNum: exports.maxNum,
minNum: exports.minNum,
minYear: exports.minYear,
letterAndNumberRequired: exports.letterAndNumberRequired,
notEqual: exports.notEqual,
passwordValidations: exports.passwordValidations,
validateDependantField: exports.validateDependantField,
validateRequiredOnField: exports.validateRequiredOnField,
validateInvalidBins: exports.validateInvalidBins,
validateCreditCard: exports.validateCreditCard,
validateAnimatedCreditCard: exports.validateAnimatedCreditCard,
validateSketch: exports.validateSketch,
validateDocumentNumber: exports.validateDocumentNumber,
validateRut: exports.validateRut,
fileSignatureValidation: exports.fileSignatureValidation,
fileSizeValidation: exports.fileSizeValidation,
sameValue: exports.sameValue,
differentValue: exports.differentValue,
documentValidation: exports.documentValidation,
validatePhoneWithChildKeys: exports.validatePhoneWithChildKeys,
checkCustomDateValidations: exports.checkCustomDateValidations,
emailRegex: regularExpressions_1.emailRegex,
validateOnlyLettersAndNumbers: exports.validateOnlyLettersAndNumbers,
validateBetweenValues: exports.validateBetweenValues,
validateCBU: exports.validateCBU,
};
exports.default = VALIDATE_UTILS;