0
votes

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
1
Can you share your objects which you want to validate? - Shahnawaz Hossan
Literally any object should be valid. The issue I have is that it doesn't throw invalid when passed nothing. I've just edited the question to mention express-joi-validation, the library I am using to add joi validators to Express endpoints - Batters
Are you sure .pattern() is supposed to take two parameters like that? If you search the documentation for "nested", you'll see that the property constraints are defined within an object passed to keys({}). I've never used Joi, so that's just my quick read for something else you could try. - Marc
If I modify my example to say .pattern(/^/, Joi.string().valid('onlythis')) and validate object {a : 1} I will get a validation error as expected so I believe my usage of .pattern is correct - Batters

1 Answers

0
votes

If you want at least one property:

joi version 17.2.1

Explanation:

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)