zod-express-middleware icon indicating copy to clipboard operation
zod-express-middleware copied to clipboard

Using the date type always fails validation

Open samislam opened this issue 1 year ago • 2 comments

If you use a date type in your zod schema as follows it will always fail validation, because JSON does not have date type, only strings, and zod will always think that string is not of type date, and thus, validation fails:

const mySchema = z.object({
  myDate: z.date()
})
import { processRequestBody} from 'zod-express-middleware'
app.get(processRequestBody(mySchema), (req,res,next)=>{ console.log("validation passed") })

Are there any plans to solve this problem?

Codesandbox here

[
  {
    "type": "Body",
    "errors": {
      "issues": [
        {
          "code": "invalid_type",
          "expected": "date",
          "received": "string",
          "path": [
            "myDate"
          ],
          "message": "Expected date, received string"
        }
      ],
      "name": "ZodError"
    }
  }
]

samislam avatar Dec 20 '23 11:12 samislam

Instead of using z.date() try using z.coerce.date(). While you may receive a string, Zod will try coerce it into a Date before performing validation. I haven't tested this against your exact use case but I do remember this working in the past for a similar issue.

AngaBlue avatar Jan 07 '24 15:01 AngaBlue

Using .coerce results in error in console + schema validation fail: The specified value "Sat Jan 01 2000 01:00:00 GMT+0100 (Central European Standard Time)" does not conform to the required format, "yyyy-MM-dd"

masar3141 avatar Sep 21 '24 07:09 masar3141