-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
z.coerce.string()
casts undefined
to "undefined" string
#2520
Comments
This is the expected behaviour, as It's recommended to initialize your form with 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)) |
I believe this is a bug. It's not obvious that this transformation may disable the
|
Well, it's definitely not a bug. As you can see in the doc, z.coerce.string(); // String(input) So of course |
Then it can be improved. Usage of It's also possible to solve this issue from the other side - make the Related: #2461 |
Well, I'd suggest using E.g. It's kind of a trade-off. If you choose |
In my opinion, this is surprising behavior, but it also interacts in surprising ways with const foo = undefined;
z.coerce.string().parse(foo);
// 'undefined'
z.coerce.string().optional().parse(foo);
// undefined
z.object({
foo: z.coerce.string(),
}).parse({});
// { foo: 'undefined' }
z.object({
foo: z.coerce.string().optional(),
}).parse({});
// {}
z.object({
foo: z.coerce.string(),
}).parse({ foo });
// { foo: 'undefined' }
z.object({
foo: z.coerce.string().optional(),
}).parse({ foo });
// { foo: undefined } |
Is this issue resolved? I'd like to close it if it is. |
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
Here are the rules:
As you can see, the field "title" is required. But in case you don't pass it at all,
coerce
fills it with "undefined" and the validation passes. And later this "undefined" gets passed into the rest of the app's logic.The text was updated successfully, but these errors were encountered: