javascripttypescriptzod

Zod - Checking the number of digits on a number type


I'm unable to figure out how to check for the number of digits in a number using Zod.

Since I'm converting my string value to a number, I'm unable to use min() or max() to check for the number of digits.

I've tried using lte() and gte() the following when building my schema:

export const MySchema = z.object({
  type1: z.coerce.string(),
  type2: z.coerce.string(),
  type4: z.coerce.number().lte(5).gte(5),
  type5: z.coerce.number()
})

My goal is to limit type4 to a fix length of 5 digits for validation. What could be an alternative solution? Maybe checking the string length before converting to a number?


Solution

  • If the number must be an integer, this can be achieved with no special transforms or preprocesses:

    // Omitting the wrapper stuff
    z.coerce.number() // Force it to be a number
      .int() // Make sure it's an integer
      .gte(10000) // Greater than or equal to the smallest 5 digit int
      .lte(99999) // Less than or equal to the largest 5 digit int
    

    If the number can be a decimal, then the other answer to this question is probably your best bet.