-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (44 loc) · 972 Bytes
/
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
'use strict';
/**
* Extend Joi with country validation
*/
const JoiCountry = Joi => ({
type: 'country',
base: Joi.string(),
messages: {
country: 'must be a valid country code',
},
coerce(value) {
value = value.toUpperCase();
return {value};
},
validate(value, helpers) {
//Get data
const {validCodes, isValid} = JoiCountry;
//Validate based on array
if (Array.isArray(validCodes) && validCodes.includes(value)) {
return;
}
//Use validator
else if (typeof isValid === 'function' && isValid(value)) {
return;
}
//Invalid
const errors = helpers.error('country');
return {value, errors};
},
});
/**
* Setter for validator
*/
JoiCountry.setValidator = function(validator) {
JoiCountry.isValid = validator;
};
/**
* Setter for array of valid country codes
*/
JoiCountry.setValidCodes = function(codes) {
JoiCountry.validCodes = codes;
};
//Export
module.exports = JoiCountry;