Skip to content

z.coerce.number() defaults empty strings to 0 #2814

Answered by edersonlucas
srowe0091 asked this question in Q&A
Discussion options

You must be logged in to vote

Using @maximeburri approach, I made a function that wraps the z.number() type you'd like :

import { z, ZodTypeAny } from 'zod';

export const zodInputStringPipe = (zodPipe: ZodTypeAny) =>
  z
    .string()
    .transform((value) => (value === '' ? null : value))
    .nullable()
    .refine((value) => value === null || !isNaN(Number(value)), {
      message: 'Nombre Invalide',
    })
    .transform((value) => (value === null ? 0 : Number(value)))
    .pipe(zodPipe);

In use :

const schema = zodInputStringPipe(z.number().positive('Le nombre doit être supérieur à 0'));

May be handier to use in your schemas

Thank you, that's exactly what I was looking for.

Replies: 17 comments 6 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
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
1 reply
@tyteen4a03
Comment options

Comment options

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

You must be logged in to vote
1 reply
@JacobWeisenburger
Comment options

Comment options

You must be logged in to vote
4 replies
@scottymccormick
Comment options

@Lukem121
Comment options

@scottymccormick
Comment options

@Lukem121
Comment options

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
Converted from issue

This discussion was converted from issue #2461 on September 27, 2023 10:20.