@malga-checkout/core
Version:
Core components for Malga Checkout
45 lines (44 loc) • 1.97 kB
JavaScript
import settings from '../settings';
import { state as credit } from './credit';
import { schema } from './credit.schema';
export const handleSubmitValidation = async () => {
var _a, _b, _c, _d;
const hasInstallments = (_d = (_c = (_b = (_a = settings.paymentMethods) === null || _a === void 0 ? void 0 : _a.credit) === null || _b === void 0 ? void 0 : _b.installments) === null || _c === void 0 ? void 0 : _c.show) !== null && _d !== void 0 ? _d : false;
const validation = await validateCreditForm(credit.form, {
hasInstallments,
});
if (!validation.isValid) {
credit.validations.fields = Object.assign(Object.assign({}, credit.validations.fields), validation.errors);
const checkedIfAllFieldsIsBlank = checkIfAllFieldsIsBlank(credit.form);
if (checkedIfAllFieldsIsBlank) {
credit.validations.allFieldsIsBlank = true;
}
}
return validation.isValid;
};
export const normalizeValidationErrors = (errors) => {
const normalizedErrors = errors.reduce((accumulatorErrors, currentError) => (Object.assign(Object.assign({}, accumulatorErrors), { [currentError.path]: currentError.message })), {});
return normalizedErrors;
};
export const checkIfAllFieldsIsBlank = (data) => {
const fields = Object.entries(data);
const filteredBlankFieldValues = fields
.map(([field, value]) => {
const isMaskedField = ['expirationDate', 'cvv'].includes(field);
const normalizedValue = field.replace(/\D/g, '').trim();
return isMaskedField ? normalizedValue : value;
})
.filter((field) => !field || field === 'none');
return fields.length === filteredBlankFieldValues.length;
};
export const validateCreditForm = async (data, context, locale) => {
try {
const cardSchema = schema(locale);
await cardSchema.validate(data, { abortEarly: false, context });
return { isValid: true };
}
catch (error) {
const errors = normalizeValidationErrors(error.inner);
return { isValid: false, errors };
}
};