-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathphone-assert.js
More file actions
83 lines (61 loc) · 1.88 KB
/
phone-assert.js
File metadata and controls
83 lines (61 loc) · 1.88 KB
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
74
75
76
77
78
79
80
81
82
83
'use strict';
/**
* Module dependencies.
*/
import { Validator, Violation } from 'validator.js';
import { includes, intersection, isArray, keys } from 'lodash';
/**
* Export `Phone`.
*/
export default function phoneAssert({ countryCode, allowedTypes } = {}) {
/**
* Peer dependency `google-libphonenumber`.
*/
const { PhoneNumberType, PhoneNumberUtil } = require('google-libphonenumber');
/**
* Phone util instance.
*/
const phoneUtil = PhoneNumberUtil.getInstance();
/**
* Class name.
*/
this.__class__ = 'Phone';
/**
* Country code to test the phone number in. May be not be set if the number is
* guaranteed to start with a '+' followed by the country calling code (E164).
*/
this.countryCode = countryCode;
/**
* The allowed phone number types.
*/
if (allowedTypes) {
if (!isArray(allowedTypes) || intersection(allowedTypes, keys(PhoneNumberType)).length !== allowedTypes.length) {
throw new Error('Phone types specified are not valid.');
}
this.allowedTypes = allowedTypes.map(type => PhoneNumberType[type]);
}
/**
* Validation algorithm.
*/
this.validate = value => {
if (typeof value !== 'string') {
throw new Violation(this, value, { value: Validator.errorCode.must_be_a_string });
}
try {
const phone = phoneUtil.parse(value, this.countryCode);
if (!phoneUtil.isValidNumber(phone)) {
throw new Error('Phone is not valid');
}
if (this.countryCode && !phoneUtil.isValidNumberForRegion(phone, this.countryCode)) {
throw new Error(`Phone does not belong to country "${this.countryCode}"`);
}
if (this.allowedTypes && !includes(this.allowedTypes, phoneUtil.getNumberType(phone))) {
throw new Error(`Phone type is not allowed`);
}
} catch (e) {
throw new Violation(this, value);
}
return true;
};
return this;
}