本文介绍了嵌套对象的Hapi/Joi验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对其中一条路线进行了以下验证:

I have the following validation on one of my routes:

payload: {
    keywordGroups: Joi.array().items(Joi.object().keys({
        language: Joi.string().required(),
        containsAny: Joi.array().items(Joi.string()).default([]).when('containsAll', { is: [], then: Joi.required() }),
        containsAll: Joi.array().items(Joi.string()).default([]).when('containsAny', { is: [], then: Joi.required() }),
        notContainsAll: Joi.array().items(Joi.string()).default([]),
        notContainsAny: Joi.array().items(Joi.string()).default([])
    })).required(),
}

我正在尝试使containsAnycontainsAll必须包含至少一个字符串.如果containsAny为空,则containsAll应该至少包含一项.如果containsAll为空,则containsAny至少应包含一项.

I'm trying to make it so that containsAny or containsAll have to include at least one string. If containsAny is empty, containsAll should have at least one item. And if containsAll is empty, containsAny should at least include one item.

但是对于对象数组,Joi.when似乎并没有真正起作用.

But it seems Joi.when doesn't really work when it comes to an array of objects.

推荐答案

您需要使用 Joi.alternatives() ,否则,您将按照.

when()中的is条件中,您需要指定Joi类型,而不只是一个空数组.此示例有效:

In your is condition in the when(), you need to specify a Joi type instead of just an empty array. This example works:

import * as Joi from 'joi';

var arraySchema = Joi.array().items(Joi.object().keys({
    first: Joi.array().items(Joi.number()).default([])
        .when('second', {is: Joi.array().length(0), then: Joi.array().items(Joi.number()).required().min(1)}),
    second: Joi.array().items(Joi.number()).default([])
}));

var altArraySchema = Joi.array().items(Joi.object().keys({
    first: Joi.array().items(Joi.number()).default([]),
    second: Joi.array().items(Joi.number()).default([])
        .when('first', {is: Joi.array().length(0), then: Joi.array().items(Joi.number()).required().min(1)}),
}));

var obj = [
    {
        first: [],
        second: []
    }
];

var finalSchema = Joi.alternatives(arraySchema, altArraySchema);

var result = Joi.validate(obj, finalSchema);

console.log(JSON.stringify(result, null, 2));

由于firstsecond为空,因此变量obj将使验证失败.将它们中的任何一个设置为非空都将通过验证检查.

The variable obj will fail the validation because both first and second are empty. Making either of them non-empty will pass the validation check.

这篇关于嵌套对象的Hapi/Joi验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!