RunKit + npm: joi

node v18.11.0
endpointsharetweet
const Joi = require("joi"); const schema1 = Joi.object({ a: Joi.number().required(), b: Joi.number().required(), c: Joi.number().required(), d: Joi.number().when("..", { // a >= 10 && b < 5 || c == 2 is: Joi.alternatives().try( Joi.object({ a: Joi.number().min(10).required(), b: Joi.number().less(5).required(), }).unknown(), Joi.object({ c: Joi.number().equal(2).required(), }).unknown() ), then: Joi.number().min(42).required(), }), }); const schema2 = Joi.object({ a: Joi.number().required(), b: Joi.number().required(), c: Joi.number().required(), d: Joi.number().when("..", { // a >= 10 && b < 5 || c == 2 is: Joi.alternatives().try( Joi.object({ a: Joi.number().min(10).required() }) .concat(Joi.object({ b: Joi.number().less(5).required() })) .unknown(), Joi.object({ c: Joi.number().equal(2).required(), }).unknown() ), then: Joi.number().min(42).required(), }), }); for (const schema of [schema1, schema2]) { [ { a: 1, b: 2, c: 3, d: 4 }, { a: 10, b: 2, c: 3, d: 4 }, { a: 10, b: 10, c: 2, d: 4 }, { a: 10, b: 2, c: 2, d: 42 }, { a: 10, b: 2, c: 2 }, { a: 1, b: 7, c: 5 } ].forEach((test, i) => { console.info(i, schema.validate(test)); }); }
Created from: https://npm.runkit.com/joi
Loading…