hapijs / joi

The most powerful data validation library for JS
Other
20.89k stars 1.51k forks source link

Joi.ref format(value) function #3017

Open efraimrodrigues opened 8 months ago

efraimrodrigues commented 8 months ago

Runtime

nodejs and https://joi.dev/tester/

Runtime version

20.10

Module version

17.12.0

Used with

No response

Any other relevant information

I've recently faced some limitations to the Joi.ref adjust(value) function.

I want to format the ref value of a date so it can be more user friendly but I'm not able to do it when the format I use cannot be parsed as a javascript Date. From the following example, new Date("28/02/2024") returns Invalid Date and I'm guessing that's the reason for the problem described below.

I know there might be some workaround by using string instead of date and having some time of regex validation, but I expected to have some type of function similar to adjust(value) that would accept any return type.

What problem are you trying to solve?

I'm trying to validate startDate and endDate. endDate must be greater than or equal to startDate.

This is the schema I've defined:

//Insert your joi schema here 
Joi.object({
  startDate: Joi.date().empty(null).required(),
  endDate: Joi.date()
    .empty(null)
    .min(
      Joi.ref("startDate", {
        render: true,
        adjust(value) {
          return new Intl.DateTimeFormat('pt-BR').format(value);
        },
      }),
    )
    .required(),
})

Note the pt-BR locale I've defined. It works with en-US.

This is the data to validate:

//Insert data to validate here 
{ 
  startDate: new Date("02/28/2024"),
  endDate: new Date("02/02/2024"),
}

This is the result I get:

{
  "startDate": "2024-02-28T03:00:00.000Z",
  "endDate" /* "endDate" date references "28/02/2024" which must have a valid date format */: "2024-02-02T03:00:00.000Z"
}

This is what I expected:

{
  "startDate": "2024-02-28T03:00:00.000Z",
  "endDate" /* "endDate" must be greater than or equal to "28/02/2024" */: "2024-02-02T03:00:00.000Z"
}

Do you have a new or modified API suggestion to solve the problem?

I can work on a PR for this.

Marsup commented 7 months ago

I need to think about it, but my 1st impression is that you're not even guaranteed that startDate is a date, so presenting information that makes sense in all circumstances seems hazardous.