question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How can I allow `null` as input value of a schema, but not as a valid output?

See original GitHub issue

I’m trying to use zod and react-hook-form together, and find it a bit difficult to deal setting defaultValues in a way that makes both react-hook-form, typescript and the actual schema validation happy.

Say you have this schema:

const zodSchema = z.number().int().nonnegative()
type ZodValues = z.input<typeof zodSchema>
// number <-- want null to be allowed here
type ZodValid = z.output<typeof zodSchema>
// number

Here both ZodValues and ZodValid does not allow null as a value.

If I add nullable, we get this:

const zodSchema = z.number().int().nonnegative().nullable()
type ZodValues = z.input<typeof zodSchema>
// number | null
type ZodValid = z.output<typeof zodSchema>
// number | null // <-- don't want null to be allowed here

Using yup@0.32.11 (latest now), it seems I’m able to do it like this, which is what I want:

const yupSchema = number().nullable(true).required().integer().min(0)
type YupValues = TypeOf<typeof yupSchema>
// number | null | undefined
type YupValid = Asserts<typeof yupSchema>
// number

Is there any way I can write this schema with zod, so that the input allows null, while the output does not?

The issue is that react-hook-form preferably wants non-undefined default values for the input, and for e.g. number and Date inputs I’d really prefer to use null as I do not want to pick a random number or date to use as the default.

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:14

github_iconTop GitHub Comments

8reactions
Svishcommented, Jun 17, 2022

Discovered the transform function gets a ctx with an addIssue function, so this seems to be a workaround of sorts…

z
    .positive()
    .nullable()
    .transform((value, ctx): number => {
      if (value == null)
        ctx.addIssue({
          code: 'custom',
          message: 'X Cannot be null',
        });
      return value ?? NaN;
    })

That gets correct type, and stops it with a validation issue. Will be quite annoying to have to add that to every nullable number though, haha.

Does zod have any way to “extend” it with custom functions? Like, is it possible to add custom stuff to the “chain”, like a .nullNotAllowed() or creditCardNumber() or something like that?

1reaction
scotttrinhcommented, Jun 16, 2022

Yeah, I think maybe that’s the crux of the issue: the two types describes valid inputs and valid outputs. It doesn’t describe the domain of expected inputs that might be sent (that is unknown really).

For my purposes, I don’t care that much about the type of the form state since forms have a very loose set of data structures compared to my much more restricted domain model. Whatever works is fine and I trust that the schema does the right thing in all of the situations such that I can “trust” the parsed output. Does that make sense? I don’t know how that squares with the various form libraries, though.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using nullability in GraphQL
A field can either be nullable or non-null, and this tells you whether or not you could receive a null value when you...
Read more >
Nulls in GraphQL: Cheatsheet - Hasura
Nulls in the query​​ Fields are always optional, whether nullable or not. In inputs, such as field arguments, nullable types are always optional...
Read more >
Dealing with null in Spark - MungingData
The Spark csv() method demonstrates that null is used for values that are unknown or missing when files are read into DataFrames. nullable ......
Read more >
Using field accessors to nullable fields - IBM
A field containing a null does not contain a value. ... 7: Specify that all fields of the output interface schema are nullable....
Read more >
Problems with adding NOT NULL columns or making nullable ...
Put simply, if a column is being added, and NULL values aren't allowed, then you must provide a value to put into every...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found