vbv/client/src/utils/phone.ts

70 lines
1.8 KiB
TypeScript

export function normalizeSwissPhoneNumber(input: string) {
return input
.replace(/\s+/g, "")
.replace("(0)", "")
.replaceAll("-", "")
.replaceAll("/", "")
.replaceAll("(", "")
.replaceAll(")", "")
.replace(/^0041/, "+41")
.replace(/^\+410/, "+41")
.replace(/^0/, "+41");
}
export function validatePhoneNumber(input: string) {
const normalized = normalizeSwissPhoneNumber(input);
if (
!normalized.startsWith("+") ||
isNaN(Number(normalized.slice(1))) ||
normalized[1] === "0"
) {
// phone number can only start with a + and must be followed by numbers
return false;
}
if (["+41", "+43", "+49", "+39", "+33", "+42"].includes(normalized.slice(0, 3))) {
if (
// Swiss and French phone numbers
(normalized.startsWith("+41") || normalized.startsWith("+33")) &&
normalized.length === 12
) {
return true;
} else if (
// German and Italian phone numbers
(normalized.startsWith("+49") || normalized.startsWith("+39")) &&
normalized.length === 13
) {
return true;
} else if (
// Austrian and Liechtenstein phone numbers
(normalized.startsWith("+43") || normalized.startsWith("+423")) &&
normalized.length === 11
) {
return true;
}
return false;
}
// every other country
if (normalized.length >= 10 || normalized.length <= 13) {
return true;
}
return false;
}
export function displaySwissPhoneNumber(input: string) {
if (input && input.length === 12 && input.startsWith("+41")) {
input = input.replace("+41", "0");
let result = "";
result += input.substring(0, 3) + " ";
result += input.substring(3, 6) + " ";
result += input.substring(6, 8) + " ";
result += input.substring(8);
return result;
}
return input;
}