Skip to content

Complex conditional validation #1917

@dnttam

Description

@dnttam

Describe the problem you are trying to fix (provide as much context as possible)

So I have the following (simplified) schema:

{
   from: 2019-01-01,
   to: 2019-02-01,
   isAnnual: true,
}

The validation I need is this if "isAnnual' is true - then make sure that the duration between "to" and "from" is no more than 364 days.

I tried to do something like this:

const from = Joi.date().max(Joi.ref('to')).format('YYYY-MM-DD').raw().required();
const to = Joi.date().format('YYYY-MM-DD').raw().required();
const isAnnual = Joi.boolean();

const getDaysInSpan = (from, to) => {
	const days =  moment(to).diff(moment(from), 'days');
	return days;
};

const event = Joi.object().keys({
	from,
	to,
	isAnnual,
}).when('isAnnual', { is: true, then: getDaysInSpan(Joi.ref('to'), Joi.ref('from')) < 365 });

Bit it doesn't work - the actual date object doesn't get to the getDaysInSpan function - the to,from are joi refs.

Can this be done?

Which API (or modification of the current API) do you suggest to solve that problem ?

Don't know

Are you ready to work on a pull request if your suggestion is accepted ?

Not at the moment.

Metadata

Metadata

Assignees

Labels

featureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions