envoc-form
Version:
Envoc form components
45 lines (41 loc) • 1.33 kB
text/typescript
/** Normalizer for converting a string into a valid phone number. */
export const phoneNumber = (value: string | undefined | null) => {
if (!value) {
return undefined;
}
const onlyNums = value.replace(/[^\d]/g, '');
if (onlyNums.length <= 3) {
return onlyNums;
}
if (onlyNums.length <= 7) {
return `${onlyNums.slice(0, 3)}-${onlyNums.slice(3)}`;
}
if (onlyNums.length <= 10) {
return `${onlyNums.slice(0, 3)}-${onlyNums.slice(3, 6)}-${onlyNums.slice(
6,
10
)}`;
}
if (onlyNums.length <= 13) {
const countryCodeLength = onlyNums.length - 10;
return `+${onlyNums.slice(0, countryCodeLength)} ${onlyNums.slice(
countryCodeLength,
3 + countryCodeLength
)}-${onlyNums.slice(
3 + countryCodeLength,
6 + countryCodeLength
)}-${onlyNums.slice(6 + countryCodeLength, onlyNums.length)}`;
}
return onlyNums;
};
/** Normalizer for converting a string into a valid zip code. Allows for XXXXX and XXXXX-XXXX format. */
export const zipCode = (value: string | undefined | null) => {
if (!value) {
return undefined;
}
const onlyNums = value.replace(/[^\d]/g, '');
if (onlyNums.length > 5) {
return onlyNums.substring(0, 5) + '-' + onlyNums.substring(5, 9);
}
return onlyNums;
};