Joi: Multi type validation

Created on 30 Jul 2014  路  4Comments  路  Source: sideway/joi

Is there a way to check if a specific parameter is a string or object and if its an object then to make sure it has x y and z as keys?

support

Most helpful comment

@leore try something like this

var Joi = require('joi');
var Assert = require('assert');

var schema = Joi.alternatives([Joi.string(), Joi.object().keys({
    x:Joi.string().required(),
    y:Joi.number().required(),
    z:Joi.boolean().required()
})]);

schema.validate('a string', function (error) {

    Assert.ifError(error);
});

schema.validate({
    x: 'a string',
    y: 34,
    z: false
}, function (error) {

    Assert.ifError(error);
});

schema.validate({
    x: 'a string'
}, function (error) {

    Assert.ok(error);
});

All 4 comments

@leore try something like this

var Joi = require('joi');
var Assert = require('assert');

var schema = Joi.alternatives([Joi.string(), Joi.object().keys({
    x:Joi.string().required(),
    y:Joi.number().required(),
    z:Joi.boolean().required()
})]);

schema.validate('a string', function (error) {

    Assert.ifError(error);
});

schema.validate({
    x: 'a string',
    y: 34,
    z: false
}, function (error) {

    Assert.ifError(error);
});

schema.validate({
    x: 'a string'
}, function (error) {

    Assert.ok(error);
});

@arb so I need this one level deeper. In this case the I want a the input to be this. Can this be adapted to the following validation case.

1) parameter "x" is required and has to be a string

or

2) parameter "x" is required by needs to be an object with params "foo" and "bar"

var schema = {
    x: Joi.alternatives([
        Joi.string(),
        Joi.object({ foo: Joi.any().required(), bar: Joi.any().required() })
    ]).require()
};
Was this page helpful?
0 / 5 - 0 ratings

Related issues

n-sviridenko picture n-sviridenko  路  3Comments

normancarcamo picture normancarcamo  路  3Comments

a-c-m picture a-c-m  路  3Comments

builtbybrayne picture builtbybrayne  路  4Comments

kevbook picture kevbook  路  4Comments