Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 598
Jamie Hunt Avatar asked Dec 30 '25 00:12

Jamie Hunt


2 Answers

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.

like image 73
Souperman Avatar answered Dec 31 '25 12:12

Souperman


I used .refine to create a custom validation logic (here is an example for validate postal code).

postalCode: z.coerce
  .number({
    required_error: 'Postal Code is required',
    invalid_type_error: 'Postal Code must be a number',
  })
  .refine((val) => `${val}`.length === 5, 'Postal Code must be 5 digit long')
like image 39
Sanka Sanjeewa Avatar answered Dec 31 '25 13:12

Sanka Sanjeewa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!