Search code examples
javascriptjoi

Ensure one of two date fields are valid with Joi


I've found solutions for a slightly different versions of my issue, but what I need is to ensure that at least one of two fields contains a valid date string. Both fields always appear in the data but sometimes only one contains a valid date string while the other is an empty string.

To be clear it should validate if either one or both of the fields contains a valid date string and fail only if neither field contains a valid date string.

I've tried this schema:

const schema = Joi.object({
  date1: Joi.date(),
  date2: Joi.date(),
})
  .or("date1", "date2");

So that this validates as expected:

const doc = {
  date1: "2023-12-01 20:00:00",
  date2: "2023-12-02 20:00:00",
};

But this fails with '"date2" must be a valid date':

const doc = {
  date1: "2023-12-01 20:00:00",
  date2: "",
};

And with this schema:

const schema = Joi.object({
  date1: Joi.date().allow(null, ""),
  date2: Joi.date().allow(null, ""),
})
  .or("date1", "date2");

This now validates:

const doc = {
  date1: "2023-12-01 20:00:00",
  date2: "",
};

But this validates as well:

const doc = {
  date1: "",
  date2: "",
};

My last ditch idea is to iterate through the the data and remove either field if it contains an empty string so that the first schema will work, but I'd rather not mangle the data that way if I can validate it with Joi that way I want. Any ideas?


Solution

  • I guess this solves your problem.

    I added "iso()" because you are trying to validate ISO 8601 date format. If you don't use "iso()" it will accept any number as a date.

    Joi.object({
      date1: Joi.date().iso().empty(""),
      date2: Joi.date().iso().empty(""),
    }).or("date1", "date2")