1 import type { FormikErrors } from 'formik';
2 import { c } from 'ttag';
4 import { validateItemErrors } from '@proton/pass/lib/validation/item';
5 import type { IdentityItemFormValues, IdentitySectionFormValues, UnsafeItemExtraField } from '@proton/pass/types';
6 import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
8 import type { ExtraFieldErrors } from './extra-field';
10 const EXTRA_FIELD_KEYS = [
11 'extraPersonalDetails',
12 'extraAddressDetails',
13 'extraContactDetails',
17 const validateExtraField = ({ fieldName }: UnsafeItemExtraField): ExtraFieldErrors => {
18 const errors: ExtraFieldErrors = {};
19 if (isEmptyString(fieldName)) errors.fieldName = c('Validation').t`Field name is required`;
23 const validateExtraFields = (values: IdentityItemFormValues): FormikErrors<IdentityItemFormValues> => {
24 const errors = EXTRA_FIELD_KEYS.reduce<FormikErrors<IdentityItemFormValues>>((acc, key) => {
25 const fieldErrors = values[key].map(validateExtraField);
26 if (fieldErrors.some((err) => Object.keys(err).length)) acc[key] = fieldErrors;
30 return Object.keys(errors).length ? errors : {};
33 /** Formik union error type narrowing */
34 export type ExtraSectionsError = { sectionFields?: ExtraFieldErrors[] };
36 const validateExtraSections = ({ extraSections }: IdentityItemFormValues): FormikErrors<IdentityItemFormValues> => {
37 const errors = extraSections.reduce<ExtraSectionsError[]>((acc, { sectionFields }, index) => {
38 const sectionErrors: ExtraSectionsError = {};
39 const fieldErrors = sectionFields.map(validateExtraField);
40 if (fieldErrors.some((error) => Object.keys(error).length)) sectionErrors.sectionFields = fieldErrors;
41 if (Object.keys(sectionErrors).length) acc[index] = sectionErrors;
46 return errors.length > 0 ? { extraSections: errors } : {};
49 export const validateIdentityForm = (values: IdentityItemFormValues): FormikErrors<IdentityItemFormValues> => ({
50 ...validateItemErrors(values),
51 ...validateExtraFields(values),
52 ...validateExtraSections(values),
55 export const validateIdentitySection = ({
57 }: IdentitySectionFormValues): FormikErrors<IdentitySectionFormValues> => {
58 const errors: FormikErrors<IdentitySectionFormValues> = {};
59 if (isEmptyString(sectionName)) errors.sectionName = c('Validation').t`Section name cannot be empty`;