Joi object schema:
import Joi from 'joi';
export const schema = Joi.object({
payway: Joi.when('productPackageType', {
is: Joi.string().valid('1', '6', '7'),
then: Joi.array().min(1).max(2).items(Joi.string().valid('alipay', 'wxpay').required())
.required()
.messages({
'array.min': 'payway is required',
'array.includesRequiredUnknowns': 'payway is not correct',
}),
otherwise: Joi.optional(),
}),
productPackageType: Joi.string().required(),
});
test file:
test.only('should validate error if productPackageType is "1" and payway is an empty array ', () => {
const v = {
payway: [],
productPackageType: '1',
};
const r = schema.validate(v);
expect(r.error?.details[0].message).toMatch('payway is required');
});
Test failed:
● validator › schema › should validate error if productPackageType is "1" and payway is an empty array
expect(received).toMatch(expected)
Expected substring: "payway is required"
Received string: "payway is not correct"
22 | };
23 | const r = schema.validate(v);
> 24 | expect(r.error?.details[0].message).toMatch('payway is required');
| ^
25 | });
26 |
27 | // test('should validate error if productPackageType is "1" and payway has invalid element', () => {
I expect Joi should validate the array length firstly then the element in the array. This means the error message should be 'payway is required' rather than 'payway is not correct'.
I don't know what is the priority of the Joi validation. Which validator is used firstly, .min(1) or .items(Joi.string().valid('alipay', 'wxpay').required())?