问题
I want to validate a field 'familymemberCount' it should be greater than equal to other fields. I tried below code, but this not allow to use ' + ' operator with Ref. How do we validate with sum of other values ?
export const familyMemberRulesSchema = Joi.object({
relationMembers: Joi.object({
motherCount: Joi.number().integer().min(0).max(5).optional(),
fatherCount: Joi.number().integer().min(0).max(5).optional(),
childrenCount: Joi.number().integer().min(0).max(5).optional()
}),
familyMemberCount: Joi.number().integer().min(0).max(15).greater(
Joi.ref('relationMembers.motherCount') +
Joi.ref('relationMembers.fatherCount') +
Joi.ref('relationMembers.childrenCount')
)
});
回答1:
The joi.ref
doesn't work this way. You need to write a custom function which takes all values and do the sum that way. Basically use adjust
function while using a Joi.ref
. Something like this.
const Joi = require("@hapi/joi");
const familyMemberRulesSchema = Joi.object({
relationMembers: Joi.object({
motherCount: Joi.number().integer().min(0).max(5).optional(),
fatherCount: Joi.number().integer().min(0).max(5).optional(),
childrenCount: Joi.number().integer().min(0).max(5).optional()
}),
familyMemberCount: Joi.number().integer().min(0).max(15).greater(
Joi.ref('relationMembers', {"adjust": relationMembers => {
return relationMembers.motherCount + relationMembers.fatherCount + relationMembers.childrenCount;
}})
)
});
const result = familyMemberRulesSchema.validate({"relationMembers": {"motherCount": 2, "fatherCount": 1, "childrenCount": 2}, "familyMemberCount": 6});
console.log(result);
const error = familyMemberRulesSchema.validate({"relationMembers": {"motherCount": 4, "fatherCount": 1, "childrenCount": 2}, "familyMemberCount": 6});
console.log(error);
来源:https://stackoverflow.com/questions/60316685/hapijs-joi-validation-validate-greater-than-from-sum-of-other-property