Reputation: 749
I am validating a GET request query string (using express-joi-validation) and require the user to pass at least one extra key value pair not directly specified in the schema.
I have tried to validate as follows:
const schema = Joi
.object({
requiredKey: Joi.string().required()
knownExtraKey: Joi.boolean()
})
.pattern(/^/, Joi.string().required())
schema.validate({requiredKey: 'A'}) // valid but shouldn't be
schema.validate({requiredKey: 'A', name: "paul"}) // valid
Upvotes: 0
Views: 375
Reputation: 2813
If you want at least one property:
joi
version 17.2.1
You need to specify the minimum keys object().min()
with the following formular: number of required properties + 1. In the example below the validation returns no error if you validate an object with 3 or 4 properties.
const Joi = require('joi');
const schema = Joi.object().keys({
one: Joi.string().required(),
two: Joi.string().required(),
three: Joi.string(),
four: Joi.string(),
}).min(3);
// works
const data1 = {
one: 'one',
two: 'two',
three: 'three',
};
console.log(schema.validate(data1).error);
// works
const data2 = {
one: 'one',
two: 'two',
three: 'three',
four: 'four',
};
console.log(schema.validate(data2).error);
// fails
const data3 = {
one: 'one',
two: 'two',
};
console.log(schema.validate(data3).error)
Upvotes: 1