fabian-hiller / valibot

The modular and type safe schema library for validating structural data 🤖
https://valibot.dev
MIT License
6.27k stars 203 forks source link

Schema with interpolated value fails #443

Closed brandonpittman closed 8 months ago

brandonpittman commented 9 months ago

I've got a schema like this that I use with Modular Forms (Qwik):

export const toISO = (d: string) =>
  d.replace(/(\d{4})(\d{2})(\d{2})/, "$1-$2-$3");

export const BirthdateSchema = object({
  birthdate: coerce(
    string([
      minLength(8),
      isoDate(),
      minValue("1900-01-01"),
      maxValue(
        `${String(new Date().getFullYear() - 5)}-01-01`
      ),
    ]),
    toISO as any
  ),
});

It works locally, but when deployed, it seems to fail on the server (Cloudflare, if that would matter). The live validation in the client works, but it seems to hit the Qwik server action and fail.

Can anyone think of a reason for that? It's not as if Cloudflare can't understand new Date().

In my testing, 19550101 worked, but my own birthdate, 19830831, fails.

When it's a hard-coded max date of 2019-01-01, everything works everywhere.

fabian-hiller commented 9 months ago

I don't know what the problem is. Are there any logs with information? Maybe the Date of your JavaScript runtime behaves differently. Also, your implementation could lead to bugs if someone passes something that isn't a string. My recommendation is to change your implementation.

import * as v from 'valibot';

export const BirthdateSchema = v.object({
  birthdate: v.string([
    v.minLength(8),
    v.toCustom((d) => d.replace(/(\d{4})(\d{2})(\d{2})/u, '$1-$2-$3')),
    v.isoDate(),
    v.minValue('1900-01-01'),
    v.maxValue(`${new Date().getFullYear() - 5}-01-01`),
  ]),
});
brandonpittman commented 9 months ago

@fabian-hiller Your solution works, so I'll go with that. I'm guess that it's something weird with Qwik and Cloudflare. Thank you very much! 🙇🏻

brandonpittman commented 8 months ago

So…it seems CF requires you to get a date object in an async function.

https://community.cloudflare.com/t/date-in-worker-is-reporting-thu-jan-01-1970-0000-gmt-0000/236503/3

fabian-hiller commented 8 months ago

You could use customAsync for that: https://valibot.dev/guides/async-validation/

brandonpittman commented 8 months ago

You could use customAsync for that: https://valibot.dev/guides/async-validation/

I did that. Forgot to mention that. Just thought I’d mention that CF requires dates to be created in async functions.