YNA
YNA

Reputation: 1

Joi Validation Schema - How to allow a set of values with Joi.valid but disallow one of them dinamically with Joi.invalid at the same time?

The problem is I need to do these validations at the same time:

  1. Validate that field 'b' is in an array of valid values

  2. Validate if the field 'b' has not the same value of 'a'

I tried these 2 validations separately and it worked fine:

1.Validate that field 'b' is in an array of valid values, this works ok:

a: Joi.string(),
b: Joi.string().valid(...validValues)

2.Validate if the field 'b' has not the same value of 'a', it works ok too:

a: Joi.string(),
b: Joi.string().invalid(Joi.ref('a'))

But when I try to validate both conditions at the same time, the second one does not work:

a: Joi.string(),
b: Joi.string().valid(...validValues).invalid(Joi.ref('a'))

For example, if "1234" is in the 'validValues' ​​array, but both 'a' and 'b' have this value, it does not return an error as expected.

const validValues = ["1234", "1111"];
const { error, value } = schema.validate({
    a: "1234",
    b: "1234",
}, 
{abortEarly: false}
);

How can I do these validations?

Upvotes: 0

Views: 76

Answers (0)

Related Questions