fabian-hiller / valibot

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

Date validation default error message #654

Closed HugeLetters closed 3 months ago

HugeLetters commented 3 months ago

When receiving an invalid date(say new Date("invalid")) what you get as an error is

Expected Date but received Date

which is really confusing I would suggest checking for invalid date case and then producing an error message like

Expected Date but received InvalidDate

I'm willing to work on a PR

My current workaround is this

const DateSchema = date((issue) => {
  if (issue.input instanceof Date) {
    return 'Expected Date but received InvalidDate';
  }

  return issue.message;
})

Given we're already handling an error input could only be a Date if it's only an invalid date but we could do a more rigorous check here like

issue.input instanceof Date && Number.isNaN(issue.input.getTime())
fabian-hiller commented 3 months ago

Thanks for bringing this up. We could easily fix this, but we have to be careful not to break the current language-neutral expected and received system, which follows a specific syntax. Instead of English words, we use symbols like ! and <= to describe both properties. Something like InvalidDate makes no sense because there is no InvalidDate data type in JavaScript. Also, Invalid Date does not work because it breaks our syntax. We could change it to !Date to produce an error message that isn't confusing, but that way it's less clear what the error actually is. I would appreciate your feedback on this.

HugeLetters commented 3 months ago

Would enclosing "Invalid Date" in quotes work? I've proposed it cause that's the way it's stringified in most environments image image

fabian-hiller commented 3 months ago

This is a good idea. The only drawback might be that it is not clear whether the input was the string "Invalid Date" or an invalid date object, but it is probably better than the current solution.

HugeLetters commented 3 months ago

We could use quotes which are not used for strings then :) If string are displayed with " then we might use ` or '

fabian-hiller commented 3 months ago

I am not sure I want to introduce a new syntax just for one case. I recommend going with "Invalid Date" until we find a better solution.

fabian-hiller commented 3 months ago

Valibot v0.33.1 is available 🎉

HugeLetters commented 3 months ago

great, thanks!