Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

Accept comma/semicolon/newline in email + domain list inputs and block silent saves

Marc Seitzb68c937b412f
diff --git a/components/datarooms/groups/add-member-modal.tsx b/components/datarooms/groups/add-member-modal.tsx
index 0d328999..c3797a2f 100644
--- a/components/datarooms/groups/add-member-modal.tsx
+++ b/components/datarooms/groups/add-member-modal.tsx
@@ -59,15 +59,17 @@ export function AddGroupMemberModal({
event.preventDefault();
event.stopPropagation();
- const inputs = inputValue
- .split(",")
- .map((input) => input.trim().toLowerCase())
- .filter((input) => input);
+ const inputs = Array.from(
+ new Set(
+ inputValue
+ .split(/[,;\n\r\t]+/)
+ .map((input) => input.trim().toLowerCase())
+ .filter((input) => input.length > 0),
+ ),
+ );
if (inputs.length === 0) return;
- setLoading(true);
-
// Separate domains and emails
const domains = inputs.filter((input) => input.startsWith("@"));
const emails = inputs.filter((input) => !input.startsWith("@"));
@@ -75,21 +77,27 @@ export function AddGroupMemberModal({
// validate emails
const invalidEmails = emails.filter((email) => !validateEmail(email));
if (invalidEmails.length > 0) {
- setLoading(false);
- toast.error("Found one or more invalid email addresses.");
+ toast.error(
+ `Found invalid email${invalidEmails.length > 1 ? "s" : ""}: ${invalidEmails
+ .slice(0, 3)
+ .join(", ")}${invalidEmails.length > 3 ? ", ..." : ""}`,
+ );
return;
}
// validate domains
const invalidDomains = domains.filter((domain) => !validateDomain(domain));
if (invalidDomains.length > 0) {
- setLoading(false);
toast.error(
- "Found one or more invalid domains. Domains should be in format @example.org",
+ `Found invalid domain${invalidDomains.length > 1 ? "s" : ""}: ${invalidDomains
+ .slice(0, 3)
+ .join(", ")}${invalidDomains.length > 3 ? ", ..." : ""}. Domains should be in format @example.org`,
);
return;
}
+ setLoading(true);
+
// POST request with emails and domains
const response = await fetch(
`/api/teams/${teamId}/datarooms/${dataroomId}/groups/${groupId}/members`,
@@ -144,13 +152,16 @@ export function AddGroupMemberModal({
onChange={handleInputChange}
rows={5}
id="email"
- placeholder="[email protected], [email protected], @example.org"
+ placeholder={`[email protected], [email protected]; @example.org
+or one entry per line`}
className="flex-1 bg-muted"
autoComplete="off"
/>
<small className="text-xs text-muted-foreground">
- Use comma to separate multiple email addresses or domains. For
- domains, use format @example.org
+ Separate multiple email addresses or domains with a comma,
+ semicolon, or new line. For domains, use the format
+ {" "}
+ <code>@example.org</code>.
</small>
</div>
diff --git a/components/links/link-sheet/allow-list-section.tsx b/components/links/link-sheet/allow-list-section.tsx
index 43937532..4fa887be 100644
--- a/components/links/link-sheet/allow-list-section.tsx
+++ b/components/links/link-sheet/allow-list-section.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { LinkPreset } from "@prisma/client";
import { CheckIcon, UsersIcon, XIcon } from "lucide-react";
@@ -6,7 +6,7 @@ import { motion } from "motion/react";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
import useVisitorGroups from "@/lib/swr/use-visitor-groups";
-import { sanitizeList } from "@/lib/utils";
+import { validateList } from "@/lib/utils";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -27,6 +27,7 @@ export default function AllowListSection({
isAllowed,
handleUpgradeStateChange,
presets,
+ setValidationError,
}: {
data: DEFAULT_LINK_TYPE;
setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;
@@ -38,6 +39,7 @@ export default function AllowListSection({
highlightItem,
}: LinkUpgradeOptions) => void;
presets: LinkPreset | null;
+ setValidationError?: (key: string, errors: string[]) => void;
}) {
const { emailProtected, allowList, visitorGroupIds } = data;
const { visitorGroups } = useVisitorGroups();
@@ -52,6 +54,26 @@ export default function AllowListSection({
allowList?.join("\n") || "",
);
+ const validation = useMemo(
+ () => validateList(allowListInput, "both"),
+ [allowListInput],
+ );
+
+ useEffect(() => {
+ if (!setValidationError) return;
+ if (enabled && emailProtected) {
+ setValidationError("allowList", validation.invalid);
+ } else {
+ setValidationError("allowList", []);
+ }
+ }, [enabled, emailProtected, validation.invalid, setValidationError]);
+
+ useEffect(() => {
+ return () => {
+ setValidationError?.("allowList", []);
+ };
+ }, [setValidationError]);
+
useEffect(() => {
if (!emailProtected && enabled) {
setEnabled(false);
@@ -77,7 +99,9 @@ export default function AllowListSection({
if (updatedEnabled) {
setData((prevData) => ({
...prevData,
- allowList: updatedEnabled ? sanitizeList(allowListInput) : [],
+ allowList: updatedEnabled
+ ? validateList(allowListInput).valid
+ : [],
emailAuthenticated: true, // Turn on email authentication
emailProtected: true, // Turn on email protection
}));
@@ -99,7 +123,7 @@ export default function AllowListSection({
if (emailProtected && enabled) {
setData((prevData) => ({
...prevData,
- allowList: sanitizeList(updatedAllowListInput),
+ allowList: validateList(updatedAllowListInput).valid,
}));
}
};
@@ -254,12 +278,30 @@ export default function AllowListSection({
<Textarea
className="focus:ring-inset"
rows={5}
- placeholder={`Enter allowed emails/domains, one per line, e.g.
+ placeholder={`Enter allowed emails/domains separated by comma, semicolon, or new line, e.g.
@example.org`}
value={allowListInput}
onChange={handleAllowListChange}
+ aria-invalid={validation.invalid.length > 0}
/>
+ {validation.invalid.length > 0 ? (
+ <p className="text-xs text-destructive">
+ The following entries are not valid emails or domains and must
+ be fixed before saving:{" "}
+ <span className="font-medium">
+ {validation.invalid.slice(0, 5).join(", ")}
+ {validation.invalid.length > 5
+ ? `, and ${validation.invalid.length - 5} more`
+ : ""}
+ </span>
+ </p>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ Separate multiple entries with a comma, semicolon, or new line.
+ Use <code>@example.org</code> to allow a whole domain.
+ </p>
+ )}
</motion.div>
)}
</div>
diff --git a/components/links/link-sheet/deny-list-section.tsx b/components/links/link-sheet/deny-list-section.tsx
index 7c9a2181..07ce5e73 100644
--- a/components/links/link-sheet/deny-list-section.tsx
+++ b/components/links/link-sheet/deny-list-section.tsx
@@ -1,10 +1,10 @@
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { LinkPreset } from "@prisma/client";
import { motion } from "motion/react";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-import { sanitizeList } from "@/lib/utils";
+import { validateList } from "@/lib/utils";
import { Textarea } from "@/components/ui/textarea";
@@ -18,6 +18,7 @@ export default function DenyListSection({
isAllowed,
handleUpgradeStateChange,
presets,
+ setValidationError,
}: {
data: DEFAULT_LINK_TYPE;
setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;
@@ -29,6 +30,7 @@ export default function DenyListSection({
highlightItem,
}: LinkUpgradeOptions) => void;
presets: LinkPreset | null;
+ setValidationError?: (key: string, errors: string[]) => void;
}) {
const { emailProtected, denyList } = data;
// Initialize enabled state based on whether denyList is not null and not empty
@@ -39,6 +41,26 @@ export default function DenyListSection({
denyList?.join("\n") || "",
);
+ const validation = useMemo(
+ () => validateList(denyListInput, "both"),
+ [denyListInput],
+ );
+
+ useEffect(() => {
+ if (!setValidationError) return;
+ if (enabled && emailProtected) {
+ setValidationError("denyList", validation.invalid);
+ } else {
+ setValidationError("denyList", []);
+ }
+ }, [enabled, emailProtected, validation.invalid, setValidationError]);
+
+ useEffect(() => {
+ return () => {
+ setValidationError?.("denyList", []);
+ };
+ }, [setValidationError]);
+
useEffect(() => {
if (!emailProtected && enabled) {
setEnabled(false);
@@ -63,7 +85,7 @@ export default function DenyListSection({
if (updatedEnabled) {
setData((prevData) => ({
...prevData,
- denyList: updatedEnabled ? sanitizeList(denyListInput) : [],
+ denyList: updatedEnabled ? validateList(denyListInput).valid : [],
emailAuthenticated: true, // Turn on email authentication
emailProtected: true, // Turn on email protection
}));
@@ -84,7 +106,7 @@ export default function DenyListSection({
if (emailProtected && enabled) {
setData((prevData) => ({
...prevData,
- denyList: sanitizeList(updatedDenyListInput),
+ denyList: validateList(updatedDenyListInput).valid,
}));
}
};
@@ -118,12 +140,30 @@ export default function DenyListSection({
<Textarea
className="focus:ring-inset"
rows={5}
- placeholder={`Enter blocked emails/domains, one per line, e.g.
+ placeholder={`Enter blocked emails/domains separated by comma, semicolon, or new line, e.g.
@example.org`}
value={denyListInput}
onChange={handleDenyListChange}
+ aria-invalid={validation.invalid.length > 0}
/>
+ {validation.invalid.length > 0 ? (
+ <p className="mt-2 text-xs text-destructive">
+ The following entries are not valid emails or domains and must
+ be fixed before saving:{" "}
+ <span className="font-medium">
+ {validation.invalid.slice(0, 5).join(", ")}
+ {validation.invalid.length > 5
+ ? `, and ${validation.invalid.length - 5} more`
+ : ""}
+ </span>
+ </p>
+ ) : (
+ <p className="mt-2 text-xs text-muted-foreground">
+ Separate multiple entries with a comma, semicolon, or new line.
+ Use <code>@example.org</code> to block a whole domain.
+ </p>
+ )}
</motion.div>
)}
</div>
diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsx
index 7635e249..6c80e592 100644
--- a/components/links/link-sheet/index.tsx
+++ b/components/links/link-sheet/index.tsx
@@ -1,7 +1,15 @@
import Link from "next/link";
import { useRouter } from "next/router";
-import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { useTeam } from "@/context/team-context";
import { PlanEnum } from "@/ee/stripe/constants";
@@ -192,8 +200,53 @@ export default function LinkSheet({
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isSaving, setIsSaving] = useState<boolean>(false);
const [currentPreset, setCurrentPreset] = useState<LinkPreset | null>(null);
+ const [validationErrors, setValidationErrors] = useState<
+ Record<string, string[]>
+ >({});
const formRef = useRef<HTMLFormElement>(null);
+ const setValidationError = useCallback(
+ (key: string, errors: string[]) => {
+ setValidationErrors((prev) => {
+ const hasErrors = errors.length > 0;
+ const wasPresent = key in prev;
+ if (!hasErrors && !wasPresent) return prev;
+ if (!hasErrors && wasPresent) {
+ const next = { ...prev };
+ delete next[key];
+ return next;
+ }
+ const previous = prev[key];
+ if (
+ previous &&
+ previous.length === errors.length &&
+ previous.every((value, index) => value === errors[index])
+ ) {
+ return prev;
+ }
+ return { ...prev, [key]: errors };
+ });
+ },
+ [],
+ );
+
+ const validationErrorEntries = useMemo(
+ () =>
+ Object.entries(validationErrors).filter(([, errors]) => errors.length > 0),
+ [validationErrors],
+ );
+ const hasValidationErrors = validationErrorEntries.length > 0;
+
+ const validationErrorLabel = useMemo(() => {
+ const labels: Record<string, string> = {
+ allowList: "Allow specified viewers",
+ denyList: "Block specified viewers",
+ };
+ return validationErrorEntries
+ .map(([key]) => labels[key] ?? key)
+ .join(", ");
+ }, [validationErrorEntries]);
+
const isPresetsAllowed =
isTrial ||
(isPro && limits?.advancedLinkControlsOnPro) ||
@@ -221,12 +274,15 @@ export default function LinkSheet({
"mod+enter",
(e) => {
e.preventDefault();
- if (!isSaving && formRef.current) {
+ if (!isSaving && !hasValidationErrors && formRef.current) {
formRef.current.requestSubmit();
}
},
- { enabled: isOpen, enableOnFormTags: true },
- [isSaving],
+ {
+ enabled: isOpen && !hasValidationErrors,
+ enableOnFormTags: true,
+ },
+ [isSaving, hasValidationErrors],
);
const handlePreviewLink = async (link: LinkWithViews) => {
@@ -314,6 +370,13 @@ export default function LinkSheet({
return;
}
+ if (hasValidationErrors) {
+ toast.error(
+ `Fix invalid emails or domains in: ${validationErrorLabel}`,
+ );
+ return;
+ }
+
setIsSaving(true);
// Upload the image if it's a data URL
@@ -732,6 +795,7 @@ export default function LinkSheet({
linkType={linkType}
editLink={!!currentLink}
currentPreset={currentPreset}
+ setValidationError={setValidationError}
/>
</div>
</TabsContent>
@@ -882,6 +946,7 @@ export default function LinkSheet({
linkType={linkType}
editLink={!!currentLink}
currentPreset={currentPreset}
+ setValidationError={setValidationError}
/>
</div>
</TabsContent>
@@ -901,22 +966,31 @@ export default function LinkSheet({
</ScrollArea>
<SheetFooter>
- <div className="flex flex-row-reverse items-center gap-2 pt-2">
- <Button
- type="submit"
- loading={isSaving}
- onClick={(e) => handleSubmit(e, false)}
- >
- {currentLink ? "Update Link" : "Save Link"}
- </Button>
- <Button
- type="button"
- variant="outline"
- loading={isLoading}
- onClick={(e) => handleSubmit(e, true)}
- >
- {currentLink ? "Update & Preview" : "Save & Preview"}
- </Button>
+ <div className="flex flex-col gap-2 pt-2">
+ {hasValidationErrors ? (
+ <p className="text-right text-xs text-destructive">
+ Fix invalid emails or domains in: {validationErrorLabel}
+ </p>
+ ) : null}
+ <div className="flex flex-row-reverse items-center gap-2">
+ <Button
+ type="submit"
+ loading={isSaving}
+ disabled={hasValidationErrors}
+ onClick={(e) => handleSubmit(e, false)}
+ >
+ {currentLink ? "Update Link" : "Save Link"}
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ loading={isLoading}
+ disabled={hasValidationErrors}
+ onClick={(e) => handleSubmit(e, true)}
+ >
+ {currentLink ? "Update & Preview" : "Save & Preview"}
+ </Button>
+ </div>
</div>
</SheetFooter>
</form>
diff --git a/components/links/link-sheet/link-options.tsx b/components/links/link-sheet/link-options.tsx
index 16e2412c..8243c167 100644
--- a/components/links/link-sheet/link-options.tsx
+++ b/components/links/link-sheet/link-options.tsx
@@ -83,6 +83,7 @@ export const LinkOptions = ({
linkType,
editLink,
currentPreset = null,
+ setValidationError,
}: {
data: DEFAULT_LINK_TYPE;
setData: React.Dispatch<React.SetStateAction<DEFAULT_LINK_TYPE>>;
@@ -90,6 +91,7 @@ export const LinkOptions = ({
linkType: Omit<LinkType, "WORKFLOW_LINK">;
editLink?: boolean;
currentPreset?: LinkPreset | null;
+ setValidationError?: (key: string, errors: string[]) => void;
}) => {
const {
isStarter,
@@ -157,6 +159,7 @@ export const LinkOptions = ({
}
handleUpgradeStateChange={handleUpgradeStateChange}
presets={currentPreset}
+ setValidationError={setValidationError}
/>
<DenyListSection
key={`deny-list-${data.id ?? "new"}`}
@@ -170,6 +173,7 @@ export const LinkOptions = ({
}
handleUpgradeStateChange={handleUpgradeStateChange}
presets={currentPreset}
+ setValidationError={setValidationError}
/>
</>
) : null}
diff --git a/components/settings/global-block-list-form.tsx b/components/settings/global-block-list-form.tsx
index 43ce8277..d82f2c87 100644
--- a/components/settings/global-block-list-form.tsx
+++ b/components/settings/global-block-list-form.tsx
@@ -4,7 +4,7 @@ import { useTeam } from "@/context/team-context";
import { toast } from "sonner";
import useSWR from "swr";
-import { fetcher, sanitizeList } from "@/lib/utils";
+import { fetcher, sanitizeList, validateList } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
@@ -38,14 +38,7 @@ export default function GlobalBlockListForm() {
}
}, [blockList]);
- const allEntered = blockListInput
- .split("\n")
- .map((d) => d.trim())
- .filter(Boolean);
- const validEntries = sanitizeList(blockListInput, "both");
- const invalidEntries = allEntered.filter(
- (d) => !validEntries.includes(d.toLowerCase()),
- );
+ const { invalid: invalidEntries } = validateList(blockListInput, "both");
const saveDisabled = useMemo(() => {
return (
@@ -101,14 +94,19 @@ export default function GlobalBlockListForm() {
<Textarea
className="focus:ring-inset"
rows={5}
- placeholder={`Enter one email or domain per line, e.g.\[email protected]\[email protected]`}
+ placeholder={`Enter emails or domains separated by comma, semicolon, or new line, e.g.\[email protected]\[email protected]`}
value={blockListInput}
onChange={(e) => setBlockListInput(e.target.value)}
+ aria-invalid={invalidEntries.length > 0}
/>
- {invalidEntries.length > 0 && (
+ {invalidEntries.length > 0 ? (
<p className="mt-2 text-sm text-destructive">
- The following entries are not valid and will be ignored:{" "}
- {invalidEntries.join(", ")}
+ The following entries are not valid and must be fixed before
+ saving: {invalidEntries.join(", ")}
+ </p>
+ ) : (
+ <p className="mt-2 text-xs text-muted-foreground">
+ Separate multiple entries with a comma, semicolon, or new line.
</p>
)}
</CardContent>
diff --git a/components/settings/ignored-domains-form.tsx b/components/settings/ignored-domains-form.tsx
index c41b7fdb..7f5ad95b 100644
--- a/components/settings/ignored-domains-form.tsx
+++ b/components/settings/ignored-domains-form.tsx
@@ -4,7 +4,7 @@ import { useTeam } from "@/context/team-context";
import { toast } from "sonner";
import useSWR from "swr";
-import { fetcher, sanitizeList } from "@/lib/utils";
+import { fetcher, sanitizeList, validateList } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
@@ -38,14 +38,7 @@ export default function IgnoredDomainsForm() {
}
}, [ignoredDomains]);
- const allEnteredDomains = domainsInput
- .split("\n")
- .map((d) => d.trim())
- .filter(Boolean);
- const validDomains = sanitizeList(domainsInput, "domain");
- const invalidDomains = allEnteredDomains.filter(
- (d) => !validDomains.includes(d.toLowerCase()),
- );
+ const { invalid: invalidDomains } = validateList(domainsInput, "domain");
const saveDisabled = useMemo(() => {
return (
@@ -100,16 +93,21 @@ export default function IgnoredDomainsForm() {
<Textarea
className="focus:ring-inset"
rows={5}
- placeholder={`Enter one domain per line, e.g.
+ placeholder={`Enter domains separated by comma, semicolon, or new line, e.g.
@company.io
@example.com`}
value={domainsInput}
onChange={(e) => setDomainsInput(e.target.value)}
+ aria-invalid={invalidDomains.length > 0}
/>
- {invalidDomains.length > 0 && (
+ {invalidDomains.length > 0 ? (
<p className="mt-2 text-sm text-destructive">
- The following entries are not valid domains and will be ignored:{" "}
- {invalidDomains.join(", ")}
+ The following entries are not valid domains and must be fixed
+ before saving: {invalidDomains.join(", ")}
+ </p>
+ ) : (
+ <p className="mt-2 text-xs text-muted-foreground">
+ Separate multiple domains with a comma, semicolon, or new line.
</p>
)}
</CardContent>
diff --git a/components/visitors/visitor-group-modal.tsx b/components/visitors/visitor-group-modal.tsx
index 0766fcec..6cf5ac4a 100644
--- a/components/visitors/visitor-group-modal.tsx
+++ b/components/visitors/visitor-group-modal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useTeam } from "@/context/team-context";
@@ -12,7 +12,7 @@ import { toast } from "sonner";
import { mutate } from "swr";
import useSWR from "swr";
-import { fetcher, sanitizeList } from "@/lib/utils";
+import { fetcher, validateList } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
@@ -79,6 +79,11 @@ export function VisitorGroupModal({
}
}, [existingGroup, open]);
+ const validation = useMemo(
+ () => validateList(emailsInput, "both"),
+ [emailsInput],
+ );
+
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
event.stopPropagation();
@@ -88,9 +93,18 @@ export function VisitorGroupModal({
return;
}
+ if (validation.invalid.length > 0) {
+ toast.error(
+ `Fix invalid emails or domains: ${validation.invalid
+ .slice(0, 3)
+ .join(", ")}${validation.invalid.length > 3 ? ", ..." : ""}`,
+ );
+ return;
+ }
+
setLoading(true);
- const emails = sanitizeList(emailsInput);
+ const emails = validation.valid;
try {
const url = existingGroup
@@ -164,16 +178,32 @@ export function VisitorGroupModal({
id="group-emails"
className="mt-1 w-full focus:ring-inset"
rows={6}
- placeholder={`Enter emails or domains, one per line, e.g.
+ placeholder={`Enter emails or domains separated by comma, semicolon, or new line, e.g.
@example.org`}
value={emailsInput}
onChange={(e) => setEmailsInput(e.target.value)}
+ aria-invalid={validation.invalid.length > 0}
/>
- <p className="mt-1 text-xs text-muted-foreground">
- Use @domain.com to allow all emails from a domain.
- </p>
+ {validation.invalid.length > 0 ? (
+ <p className="mt-1 text-xs text-destructive">
+ The following entries are not valid emails or domains and
+ must be fixed before saving:{" "}
+ <span className="font-medium">
+ {validation.invalid.slice(0, 5).join(", ")}
+ {validation.invalid.length > 5
+ ? `, and ${validation.invalid.length - 5} more`
+ : ""}
+ </span>
+ </p>
+ ) : (
+ <p className="mt-1 text-xs text-muted-foreground">
+ Separate multiple entries with a comma, semicolon, or new
+ line. Use <code>@domain.com</code> to allow all emails from a
+ domain.
+ </p>
+ )}
</div>
{existingGroup && (
@@ -243,7 +273,12 @@ [email protected]
)}
</div>
<DialogFooter className="mt-4">
- <Button type="submit" loading={loading} className="h-9 w-full">
+ <Button
+ type="submit"
+ loading={loading}
+ disabled={validation.invalid.length > 0}
+ className="h-9 w-full"
+ >
{existingGroup ? "Update Group" : "Create Group"}
</Button>
</DialogFooter>
diff --git a/lib/utils.ts b/lib/utils.ts
index 845cb162..d63d1be9 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -653,26 +653,68 @@ export function decryptEncrpytedPassword(password: string): string {
type FilterMode = "email" | "domain" | "both";
-export const sanitizeList = (
+const LIST_SEPARATOR_REGEX = /[,;\n\r\t]+/;
+
+export type ListValidation = {
+ /** All entries entered by the user (de-duplicated, lower-cased). */
+ all: string[];
+ /** Subset of `all` that passes validation for the requested mode. */
+ valid: string[];
+ /** Subset of `all` that did NOT pass validation. */
+ invalid: string[];
+};
+
+/**
+ * Splits a free-form text list of emails / domains by any combination of
+ * comma, semicolon, newline, carriage return, or tab characters and
+ * returns the unique, validated entries.
+ *
+ * Splits with the following separators: `,`, `;`, `\n`, `\r`, `\t`.
+ */
+export const validateList = (
list: string,
mode: FilterMode = "both",
-): string[] => {
+): ListValidation => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const domainRegex = /^@[^\s@]+\.[^\s@]+$/;
- const sanitized = list
- .split("\n")
- .map((item) => item.trim().replace(/,$/, "").toLowerCase())
- .filter((item) => item !== "")
- .filter((item) => {
- if (mode === "email") return emailRegex.test(item);
- if (mode === "domain") return domainRegex.test(item);
- return emailRegex.test(item) || domainRegex.test(item);
- });
+ const isValid = (item: string): boolean => {
+ if (mode === "email") return emailRegex.test(item);
+ if (mode === "domain") return domainRegex.test(item);
+ return emailRegex.test(item) || domainRegex.test(item);
+ };
- return [...new Set(sanitized)];
+ const seen = new Set<string>();
+ const all: string[] = [];
+ const valid: string[] = [];
+ const invalid: string[] = [];
+
+ for (const raw of list.split(LIST_SEPARATOR_REGEX)) {
+ const item = raw.trim().toLowerCase();
+ if (!item) continue;
+ if (seen.has(item)) continue;
+ seen.add(item);
+ all.push(item);
+ if (isValid(item)) {
+ valid.push(item);
+ } else {
+ invalid.push(item);
+ }
+ }
+
+ return { all, valid, invalid };
};
+/**
+ * Backwards-compatible helper that returns only the valid, de-duplicated
+ * entries from a free-form list. Accepts comma, semicolon, newline,
+ * carriage return, and tab as separators.
+ */
+export const sanitizeList = (
+ list: string,
+ mode: FilterMode = "both",
+): string[] => validateList(list, mode).valid;
+
export function hexToRgb(hex: string) {
let bigint = parseInt(hex.slice(1), 16);
let r = ((bigint >> 16) & 255) / 255; // Convert to 0-1 range