UNPKG

2.17 kBJavaScriptView Raw
1import Metadata from './metadata'
2import checkNumberLength from './helpers/checkNumberLength'
3
4export default function isPossiblePhoneNumber(input, options, metadata) {
5 /* istanbul ignore if */
6 if (options === undefined) {
7 options = {}
8 }
9
10 metadata = new Metadata(metadata)
11
12 if (options.v2) {
13 if (!input.countryCallingCode) {
14 throw new Error('Invalid phone number object passed')
15 }
16 metadata.selectNumberingPlan(input.countryCallingCode)
17 } else {
18 if (!input.phone) {
19 return false
20 }
21 if (input.country) {
22 if (!metadata.hasCountry(input.country)) {
23 throw new Error(`Unknown country: ${input.country}`)
24 }
25 metadata.country(input.country)
26 } else {
27 if (!input.countryCallingCode) {
28 throw new Error('Invalid phone number object passed')
29 }
30 metadata.selectNumberingPlan(input.countryCallingCode)
31 }
32 }
33
34 if (metadata.possibleLengths()) {
35 return isPossibleNumber(input.phone || input.nationalNumber, metadata)
36 } else {
37 // There was a bug between `1.7.35` and `1.7.37` where "possible_lengths"
38 // were missing for "non-geographical" numbering plans.
39 // Just assume the number is possible in such cases:
40 // it's unlikely that anyone generated their custom metadata
41 // in that short period of time (one day).
42 // This code can be removed in some future major version update.
43 if (input.countryCallingCode && metadata.isNonGeographicCallingCode(input.countryCallingCode)) {
44 // "Non-geographic entities" did't have `possibleLengths`
45 // due to a bug in metadata generation process.
46 return true
47 } else {
48 throw new Error('Missing "possibleLengths" in metadata. Perhaps the metadata has been generated before v1.0.18.');
49 }
50 }
51}
52
53export function isPossibleNumber(nationalNumber, metadata) { //, isInternational) {
54 switch (checkNumberLength(nationalNumber, metadata)) {
55 case 'IS_POSSIBLE':
56 return true
57 // This library ignores "local-only" phone numbers (for simplicity).
58 // See the readme for more info on what are "local-only" phone numbers.
59 // case 'IS_POSSIBLE_LOCAL_ONLY':
60 // return !isInternational
61 default:
62 return false
63 }
64}
\No newline at end of file