-
Notifications
You must be signed in to change notification settings - Fork 13
/
phone-number.ts
40 lines (26 loc) · 1.2 KB
/
phone-number.ts
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
import PhoneValidator from 'awesome-phonenumber';
import { toString, isString } from './strings';
import { isNumber, inNumberRange } from './numbers';
export function parsePhoneNumber(input: string|number): string {
const preppedInput = _prepPhoneNumber(toString(input).trim());
const fullNumber = new PhoneValidator(preppedInput).getNumber();
if (fullNumber) return String(fullNumber).slice(1);
throw Error('Could not determine the incoming phone number');
}
function _prepPhoneNumber(input: string): string {
let testNumber = input;
if (testNumber.charAt(0) === '0') testNumber = testNumber.slice(1);
if (testNumber.charAt(0) !== '+') testNumber = `+${testNumber}`;
return testNumber;
}
export function isISDN(input: unknown, country?: string): boolean {
if (isString(input) || isNumber(input)) {
const isdn = country ? new PhoneValidator(toString(input), country) : new PhoneValidator(`+${input}`);
return isdn.isValid();
}
return false;
}
export function isPhoneNumberLike(input: unknown): boolean {
const testValue = toString(input).trim().replace(/\D/g, '');
return inNumberRange(testValue.length, { min: 7, max: 20, inclusive: true });
}