link-stack/apps/link/app/(main)/admin/metamigo/_lib/phone-numbers.ts

31 lines
813 B
TypeScript
Raw Normal View History

2023-02-13 12:41:30 +00:00
import { regex } from "react-admin";
export const E164Regex = /^\+[1-9]\d{1,14}$/;
/**
* Returns true if the number is a valid E164 number
*/
2023-06-07 11:18:58 +00:00
export const isValidE164Number = (phoneNumber: string) =>
E164Regex.test(phoneNumber);
2023-02-13 12:41:30 +00:00
/**
* Given a phone number approximation, will clean out whitespace and punctuation.
*/
2023-03-15 12:17:43 +00:00
export const sanitizeE164Number = (phoneNumber: string) => {
2023-02-13 12:41:30 +00:00
if (!phoneNumber) return "";
if (!phoneNumber.trim()) return "";
const sanitized = phoneNumber
2023-05-25 08:57:24 +00:00
.replaceAll(/\s/g, "")
.replaceAll(".", "")
.replaceAll("-", "")
.replaceAll("(", "")
.replaceAll(")", "");
2023-02-13 12:41:30 +00:00
if (sanitized[0] !== "+") return `+${sanitized}`;
return sanitized;
};
export const validateE164Number = regex(
E164Regex,
"Must start with a + and have no punctunation and no spaces."
);