hapijs joi validation , validate greater than from sum of other property

爱⌒轻易说出口 提交于 2021-01-28 20:26:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!