Files
community-rule/lib/create/isValidCreateFlowSaveEmail.ts
T

38 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** RFC 5321 max mailbox length (no angle brackets). */
export const EMAIL_MAX_LEN = 254;
/**
* Fallback when `HTMLInputElement.checkValidity()` is unavailable (SSR).
* Matches the HTML living standard’s type=email pattern closely enough
* for the save-progress field; the live input is the source of truth in
* the browser.
*/
const EMAIL_FALLBACK_PATTERN =
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/**
* Whether a create-flow save-progress email would pass a required
* `type="email"` input’s `checkValidity()`. Does not trim: native
* validity rejects leading or trailing spaces.
*/
export function isValidCreateFlowSaveEmail(value: unknown): boolean {
if (typeof value !== "string") return false;
if (value.length === 0 || value.length > EMAIL_MAX_LEN) return false;
// Native type=email rejects whitespace; jsdom’s checkValidity does not.
if (/\s/.test(value)) return false;
if (typeof document === "undefined") {
if (!EMAIL_FALLBACK_PATTERN.test(value)) return false;
} else {
const input = document.createElement("input");
input.type = "email";
input.required = true;
input.value = value;
if (!input.checkValidity()) return false;
}
// Native type=email allows a single domain label (`maya@example`). The
// save-progress field needs a dotted domain so we can actually send mail.
const at = value.lastIndexOf("@");
const domain = at >= 0 ? value.slice(at + 1) : "";
return domain.includes(".");
}