2025-10-25 11:39:24 +02:00

50 lines
1.4 KiB
TypeScript

import { PHONE_REGEX } from "./constants";
// Phone validation function
export const validatePhone = (phone: string, countryCode: string): string => {
if (!phone) return ""; // Phone is optional
// Remove any non-digit characters except +
const cleanPhone = phone.replace(/[^\d+]/g, "");
// Check if phone starts with country code
if (cleanPhone.startsWith(countryCode)) {
const phoneNumber = cleanPhone.substring(countryCode.length);
if (phoneNumber.length < 7 || phoneNumber.length > 15) {
return "Phone number must be between 7-15 digits";
}
if (!PHONE_REGEX.test(phoneNumber)) {
return "Invalid phone number format";
}
} else {
// If phone doesn't start with country code, validate the whole number
if (cleanPhone.length < 7 || cleanPhone.length > 15) {
return "Phone number must be between 7-15 digits";
}
if (!PHONE_REGEX.test(cleanPhone)) {
return "Invalid phone number format";
}
}
return "";
};
// Format phone number display
export const formatPhoneDisplay = (
phone: string,
countryCode: string
): string => {
if (!phone) return "";
// Remove any non-digit characters except +
const cleanPhone = phone.replace(/[^\d+]/g, "");
// If phone already includes country code, return as is
if (cleanPhone.startsWith(countryCode)) {
return cleanPhone;
}
// Otherwise, prepend country code
return `${countryCode}${cleanPhone}`;
};