-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (78 loc) · 2.32 KB
/
index.js
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
84
"use strict";
const { Country, State } = require("country-state-city");
const countryStateValidator = (joi) => ({
type: "string",
base: joi.string(),
messages: {
"country.invalid": "{{#label}} is not a valid country",
"state.countryRequired":
"A valid country is required to validate the state",
"state.invalid":
"{{#label}} must be a valid state code for the selected country",
},
rules: {
country: {
method() {
return this.$_addRule("country");
},
validate(value, helpers) {
if (!Country.getCountryByCode(value)) {
return helpers.error("country.invalid");
}
return value;
},
},
state: {
method(country, countryStatesConfig) {
return this.$_addRule({
name: "state",
args: { country, countryStatesConfig },
});
},
args: [
{
name: "country",
ref: true,
assert: (value) => typeof value === "string",
message: "must be a string",
},
{
name: "countryStatesConfig",
assert: (value) => {
if (value === undefined) return true;
if (typeof value !== "object") return false;
return Object.entries(value).every(([, states]) => {
if (!Array.isArray(states)) {
return false;
}
return true;
});
},
message:
"must be an object with country codes as keys and arrays of states as values",
},
],
validate(value, helpers, args) {
const country = args.country;
const countryStatesConfig = args.countryStatesConfig;
if (!country) {
return helpers.error("state.countryRequired");
}
if (countryStatesConfig) {
if (
!countryStatesConfig[country] ||
!countryStatesConfig[country].includes(value)
) {
return helpers.error("state.invalid");
}
} else {
if (!State.getStateByCodeAndCountry(value, country)) {
return helpers.error("state.invalid");
}
}
return value;
},
},
},
});
module.exports = countryStateValidator;