hapijs joi验证,比从其他属性的总和验证更大 [英] hapijs joi validation , validate greater than from sum of other property

查看:81
本文介绍了hapijs joi验证,比从其他属性的总和验证更大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证字段"familymemberCount",该字段应大于其他字段.我尝试了下面的代码,但是这不允许在Ref中使用'+'运算符.如何验证其他值的总和?

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') 
    )
});

推荐答案

joi.ref 不能以这种方式工作.您需要编写一个自定义函数,该函数接受所有值并以这种方式求和.基本上在使用 Joi.ref 时使用 adjust 函数.像这样的东西.

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);


这篇关于hapijs joi验证,比从其他属性的总和验证更大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆