Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 1x 1x | import constants, { formatTypes } from "./constants";
import formatted_ from "./format";
import splitByIndex from "./helpers/splitByIndex";
import checkPhoneValidity from "./helpers/checkPhoneValidity";
import emptyReturn from "./constants/emptyReturn";
type formatType = string | null;
export interface ReturnValues {
isValid: boolean;
telco: string | null;
short: formatType;
normalized: formatType;
error?: string | null;
dashed: formatType;
formatted: formatType;
unformatted: formatType;
format: (shape?: formatTypes) => string;
}
export type PhoneNumberType = (phoneNumber: string) => ReturnValues;
const phoneUtils: PhoneNumberType = (phoneNumber) => {
Eif (!phoneNumber) return emptyReturn;
const phone = phoneNumber?.replace(/[^\d.-]/g, "");
const unformatted = `${phone}`?.substring(
`${phone}`.length - constants.shortLength
);
const phoneTelco = constants?.telcos?.find((t) =>
unformatted.startsWith(`${t.value}`)
);
const { isValid, message: errorMessage } = checkPhoneValidity(
phone,
phoneTelco
);
return {
isValid,
error: isValid ? null : errorMessage,
normalized: isValid ? `250${unformatted}` : null,
formatted: isValid
? `+(${constants.prefix}) ${splitByIndex(unformatted, 3)}`
: null,
unformatted: isValid ? `${constants.prefix}${unformatted}` : phoneNumber,
telco: phoneTelco ? phoneTelco?.label : null,
short: isValid ? unformatted : null,
dashed: isValid
? `+(${constants.prefix})-${splitByIndex(unformatted, 3, "dash")}`
: null,
format(shape) {
return this.isValid ? formatted_(unformatted, shape) : constants.errors.invalid
},
};
};
export default phoneUtils;
// TODO
// - configure eslint and prettier
// - refactor format
// - add all possible format
|