1 import type { FormikErrors } from 'formik';
2 import { c } from 'ttag';
4 import type { UrlGroupValues } from '@proton/pass/types';
5 import { duplicates } from '@proton/pass/utils/array/duplicate';
6 import { isEmptyString } from '@proton/pass/utils/string/is-empty-string';
7 import { sanitizeURL } from '@proton/pass/utils/url/sanitize';
9 /* validates the active URL input field */
10 export const validateUrl = <V extends UrlGroupValues>({ url, urls }: V) => {
11 if (!isEmptyString(url)) {
12 const { valid: validURL, url: safeUrl } = sanitizeURL(url);
13 const urlExists = urls.map(({ url }) => url).includes(safeUrl);
15 if (!validURL) return { url: c('Validation').t`URL is invalid` };
16 if (urlExists) return { url: c('Validation').t`URL already exists` };
22 /* validates the actual URLs list */
23 export const validateUrls = <V extends UrlGroupValues>({ urls }: V) => {
24 const duplicatesCount = duplicates(urls.map((item) => item.url));
26 const urlsErrors = urls.map(({ url }) => {
27 const isEmpty = isEmptyString(url);
28 const { valid: validURL, url: safeUrl } = sanitizeURL(url);
30 if (isEmpty) return { url: c('Validation').t`URL cannot be empty` };
31 if (!validURL) return { url: c('Validation').t`URL is invalid` };
32 if ((duplicatesCount.get(safeUrl) ?? 0) > 1) return { url: c('Validation').t`Duplicated URL` };
37 return (urlsErrors.some(({ url }) => url !== undefined) ? { urls: urlsErrors } : {}) as FormikErrors<V>;