-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.ts
More file actions
54 lines (45 loc) · 2.05 KB
/
validate.ts
File metadata and controls
54 lines (45 loc) · 2.05 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
import type { TextField, Validate } from 'payload';
import libphonenumber from 'google-libphonenumber';
const { PhoneNumberUtil } = libphonenumber;
import type { RegionCode } from '../types.js';
let phoneUtil: libphonenumber.PhoneNumberUtil | null = null;
export const createPhoneNumberValidator = (allowedCountries?: RegionCode[]): Validate<string, unknown, unknown, TextField> => {
return (value, { req, required }) => {
if (!phoneUtil) {
phoneUtil = PhoneNumberUtil.getInstance();
}
if (!value) {
if (required) {
return req.t('validation:required');
}
return true;
}
let phoneNumberValue: string;
if (typeof value === 'string') {
phoneNumberValue = value;
} else if (typeof value === 'object' && value !== null && 'e164' in value) {
phoneNumberValue = (value as { e164: string }).e164;
} else {
// @ts-expect-error - translations are not typed in plugins yet
return req.t('payload-phone-number-plugin:phoneNumberMustBeString');
}
try {
const number = phoneUtil.parse(phoneNumberValue);
if (!phoneUtil.isValidNumber(number)) {
// @ts-expect-error - translations are not typed in plugins yet
return req.t('payload-phone-number-plugin:invalidPhoneNumber');
}
if (allowedCountries && allowedCountries.length > 0) {
const regionCode = phoneUtil.getRegionCodeForNumber(number);
if (regionCode && !allowedCountries.includes(regionCode as RegionCode)) {
// @ts-expect-error - translations are not typed in plugins yet
return req.t('payload-phone-number-plugin:phoneNumberCountryNotAllowed');
}
}
return true;
} catch {
// @ts-expect-error - translations are not typed in plugins yet
return req.t('payload-phone-number-plugin:invalidPhoneNumberFormat');
}
};
};