Skip to content

z.coerce.string() casts undefined to "undefined" string #2804

Answered by xsjcTony
andrew-sol asked this question in Q&A
Discussion options

You must be logged in to vote

This is the expected behaviour, as corece under the hood runs String(input).

It's recommended to initialize your form with '' or write your own transform logic, e.g.

title: z.any()
  .transform(val => val == null ? '' : val.toString())
  .pipe(z.string().min(1))

Or you can implement your own preprocessor

title: z.preprocess(val => val == null ? '' : val.toString(), z.string().min(1))

Replies: 7 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by JacobWeisenburger
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants
Converted from issue

This discussion was converted from issue #2520 on September 25, 2023 13:56.