How can I make a yup number accept nullable values?
Asked Answered
A

2

42

I have the following yup check:

nrOfApples: yup.number().min(0).max(999),

And right now if I leave the field blank, it validates as false. Is there any way to make yup.number() accept empty values? I have tried:

yup.number().nullable()

But it doesn't seem to work. Any ideas on how I can make such thing happen?

Aquamarine answered 3/8, 2020 at 13:36 Comment(0)
I
73

You have to pass true to nullable -

nrOfApples: yup.number().min(0).max(999).nullable(true);

From: https://github.com/jquense/yup/issues/500

Working example: https://runkit.com/xdumaine/5f2816c75a0ba5001aa312b2

Note that if you add required().nullable(true) the required overrides the nullable and null will not validate.

Update:

You can use a transform to convert the NaN value into null. I updated the runkit with this:

const contactSchema = yup.object({
  name: yup.string()
    .required(),
  nrOfApples: yup
    .number()
    .min(0)
    .max(999)
    .nullable(true)
    // checking self-equality works for NaN, transforming it to null
    .transform((_, val) => val === Number(val) ? val : null) 
})
Izard answered 3/8, 2020 at 13:58 Comment(4)
Hi @xdumaine, thanks for your response. However, when the field is left as empty, the value that it returns is NaN instead of null, so .nullable(true) is not working in this case.Aquamarine
The suggested solution did not work for me but thankfully the runkit link provided contained a change. I will suggest an edit but just in case swap the transform function call to the following .transform((_, val) => val ? Number(val) : null)Leaguer
@Izard Thanks for amazing answer, very comman to come this situation but very challaging with Yup library to validate number fields.Creeps
This works up until someone enters some nonsense like -+1e into the number input, which will behind the scenes converts to null (imo not good ux). Can't tell the difference between nonsense and a null input in the transform bc they both are passed in as NaNSotted
M
3

also this worked for me,

validation: yup.string().nullable()
Marj answered 11/1 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.