i am trying to validate the string using the JOI package available in npm, i checked this documentation which has many useful string formats e.g. date, IP, base64 but i need to validate the following JSON which contains a stringified JSON as a value, and there is no example in the documentation for such case
JavaScript
x
8
1
{
2
"id": 232,
3
"name": "Trojan Horse",
4
"file": "download.exe",
5
"infected": true,
6
"engines": "['Norton', 'AVG', 'NOD32']"
7
}
8
So for example what if i want to check engines
have valid JSON value and have at-least one engine defined if infected
key is set to true
The following schema works only if the engines
value is written as parsed JSON
JavaScript
1
11
11
1
Joi.object().keys({
2
id: Joi.number().required(),
3
name: Joi.string().min(5).required(),
4
file: Joi.string().min(3).required(),
5
infected: Joi.boolean().required(),
6
engines: Joi.array().when('infected', {
7
is: Joi.exists().valid(true),
8
then: Joi.min(1).required()
9
})
10
});
11
Advertisement
Answer
What you need to do is to create a custom JOI validator by extending the array validator of the JOI package and using that custom validator for the engines property.
JavaScript
1
50
50
1
const custom = Joi.extend({
2
type: 'array',
3
base: Joi.array(),
4
coerce: {
5
from: 'string',
6
method(value, helpers) {
7
8
if (typeof value !== 'string' ||
9
value[0] !== '[' && !/^s*[/.test(value)) {
10
11
return;
12
}
13
14
try {
15
return { value: JSON.parse(value) };
16
}
17
catch (ignoreErr) { }
18
}
19
}
20
});
21
22
const schema = Joi.object({
23
id: Joi.number().required(),
24
name: Joi.string().min(5).required(),
25
file: Joi.string().min(3).required(),
26
infected: Joi.boolean().required(),
27
engines: custom.array().when('infected', {
28
is: true,
29
then: custom.array().min(1).required()
30
})
31
})
32
33
const validateTest = async (joiSchema, testObject) => {
34
try {
35
const value = await joiSchema.validateAsync(testObject);
36
console.log(value);
37
}
38
catch (err) {
39
console.error(err)
40
}
41
};
42
43
validateTest(schema, {
44
"id": 232,
45
"name": "Trojan Horse",
46
"file": "download.exe",
47
"infected": true,
48
"engines": `["Norton", "AVG", "NOD32"]`
49
})
50
You can see more examples like that here