Aquila169 / zod-express-middleware

Express middleware to validate requests using zod schema's.
MIT License
86 stars 13 forks source link

Using the date type always fails validation #15

Open samislam opened 9 months ago

samislam commented 9 months ago

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"
    }
  }
]
AngaBlue commented 9 months ago

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.

masar3141 commented 2 weeks ago

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"