最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JOI - Validating complex object - Stack Overflow

programmeradmin1浏览0评论

I tried, and tried but can't figure it :(

This is the object I need to validate:

let body = {
    greeting:
        {
            stringValue: 'Hello !',
            stringListValues: [],
            binaryListValues: [],
            dataType: 'String'
        },
    newsletterId:
        {
            stringValue: '123456789',
            stringListValues: [],
            binaryListValues: [],
            dataType: 'String'
        }
};

I need to validate that there is a greeting, and that is has key stringValue and that is not empty. Other values I don't care.

Also, for the second object newsletterId, and that also has key stringValue and that is not empty. Other values I don't care.

I have e up with checking only root object, with this schema:

const schema = {
    greeting: Joi.required(),
    newsletterId: Joi.required()
};

I read many examples, but I was unable to find none that has this type of structure.

I tried, and tried but can't figure it :(

This is the object I need to validate:

let body = {
    greeting:
        {
            stringValue: 'Hello !',
            stringListValues: [],
            binaryListValues: [],
            dataType: 'String'
        },
    newsletterId:
        {
            stringValue: '123456789',
            stringListValues: [],
            binaryListValues: [],
            dataType: 'String'
        }
};

I need to validate that there is a greeting, and that is has key stringValue and that is not empty. Other values I don't care.

Also, for the second object newsletterId, and that also has key stringValue and that is not empty. Other values I don't care.

I have e up with checking only root object, with this schema:

const schema = {
    greeting: Joi.required(),
    newsletterId: Joi.required()
};

I read many examples, but I was unable to find none that has this type of structure.

Share Improve this question asked Feb 7, 2019 at 16:40 Amiga500Amiga500 6,14111 gold badges71 silver badges119 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

lets define a schema :

const schema = Joi.object().keys({
    greeting: Joi.object({
       stringValue: Joi.string().required().empty(['', null]),
       stringListValues: Joi.array().items(Joi.string()),
       binaryListValues: Joi.array().items(Joi.binary())
    }).required(),
    newsletterId: // same as above
});

and test it like this :

Joi.validate(myObjectToTest, schema, function(error, cleanObject){
    console.log(error, cleanObject);
})

Full reference can be found here https://github./hapijs/joi/blob/master/API.md

发布评论

评论列表(0)

  1. 暂无评论