hapijs / hapijs/joi

Joi.ref format(value) function

Open
#3,017 1 comment 0 reactions 0 assignees View on GitHub
feature
Dominant language
JavaScript
Stars
21.2k
Forks
1.5k
Avg merge
4h 57m
Merged PRs (30d)
14

Description

### 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](https://joi.dev/api/?v=17.12.0#refkey-options).

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.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.