-
Notifications
You must be signed in to change notification settings - Fork 0
/
phone_numbers.ts
73 lines (61 loc) · 1.69 KB
/
phone_numbers.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import libphonenumber from 'google-libphonenumber'
import {
isValidPhoneNumber,
findPhoneNumbersInText,
parsePhoneNumberWithError,
} from 'libphonenumber-js'
const phoneUtil = libphonenumber.PhoneNumberUtil.getInstance()
const PNF = libphonenumber.PhoneNumberFormat
const AUSTRALIA = 'AU'
export const isValidNumber = (value: string) => {
if (!value) return false
try {
return isValidPhoneNumber(value, AUSTRALIA)
} catch (err) {
try {
// fallback to google-libphonenumber
const valid = phoneUtil.isValidNumberForRegion(
phoneUtil.parse(value, AUSTRALIA),
AUSTRALIA
)
return valid
} catch (err) {
return value
}
}
}
export const formatNumber = (
value: string,
format: 'national' | 'e164' = 'national'
) => {
if (!value) return ''
try {
if (typeof value !== 'string') return ''
const phoneNumber = parsePhoneNumberWithError(value, AUSTRALIA)
return format === 'national'
? phoneNumber.formatNational()
: phoneNumber.format('E.164')
} catch (err) {
try {
// fallback to google-libphonenumber
const proto = phoneUtil.parse(value, AUSTRALIA)
const shape = format === 'national' ? PNF.NATIONAL : PNF.E164
value = phoneUtil.format(proto, shape)
return value
} catch (err) {
throw new TypeError(
`Value is not a valid phone number of the form 0412 345 678 (7-15 digits): ${value}`
)
}
}
}
export const findPhoneNumbers = (value: string) => {
if (!value) return []
try {
if (typeof value !== 'string') return []
const phoneNumbers = findPhoneNumbersInText(value, AUSTRALIA)
return phoneNumbers
} catch (err) {
return []
}
}