Yup optional field validate number - React Hook Form

Viewed 384

So I have this field:

<input type="number" {...register('price')}>

And then the resolver:

{
    price: yup
      .number()
      .typeError('Must be numeric.')
      .min(1, 'Minimum $1')
      .max(999999, 'Maximum $999.999')
      .optional()
      .nullable()
}

But it still shows:

price: must be a `number` type, but the final value was: `NaN` (cast from the value `""`).

When submitting the form...

2 Answers

Here is a solution:

price: yup
  .number()
  .typeError('Must be numeric.')
  .integer('Error message')
  .min(1, 'Minimum $1')
  .max(999999, 'Maximum $999.999')
  .transform((value) => (isNaN(value) ? undefined : value))
  .nullable()
  .optional()

This is what worked for me in a similar scenario;

condition1: boolean(),
condition2: boolean(),
condition3: number().when(['condition1', 'condition2'], {
    is: (condition1: boolean, condition2: boolean) => condition1 || condition2,
    then: number.required('You must enter condition1'),
    otherwise: number()
      .optional()
      .transform(value => (isNaN(value) ? undefined : value))
      .nullable(true),
  })
Related