Joi object validation: How to validate values with unknown key names?

Try this. It’ll basically accept any key within an object campaign and the value must validate against Joi.date().iso()

campaign: Joi.object().pattern(/^/, Joi.date().iso())

This however will match any key. You can restrict this by padding out the regex a little. e.g. only word characters between 2 and 25 chars

campaign: Joi.object().pattern(/\w{2,25}/, Joi.date().iso())

UPDATE

Regarding the example in the Joi docs, I haven’t tested it but here’s my interpretation. I can understand that it’s not the most straightforward example they could have given…

const schema = Joi.object({
    arg: Joi.string().valid('firstname', 'lastname', 'title', 'company', 'jobtitle'),
    value: Joi.string(),
}).pattern(/firstname|lastname/, Joi.string().min(2));

The objects to validate must contain the two attributes arg and valuewhere arg‘s value can be one of 'firstname', 'lastname', 'title', 'company', 'jobtitle' and value is just a string.

{
    arg: 'firstname',
    value: 'john'
}

{
    arg: 'lastname',
    value: 'smith'
}

{
    arg: 'jobtitle',
    value: 'brewer'
}

However it will also allow the object to have the attributes firstname and lastname where both of their values is a string with more than two characters. So the above examples could be condensed into a single valid object.

{
    firstname: 'john',
    lastname: 'smith',
    arg: 'jobtitle',
    value: 'brewer'
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)