Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
70
rated 0 times [  75] [ 5]  / answers: 1 / hits: 48789  / 4 Years ago, mon, august 3, 2020, 12:00:00

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?


More From » yup

 Answers
10

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)
})

[#50745] Wednesday, July 22, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maurodannyr

Total Points: 126
Total Questions: 103
Total Answers: 105

Location: Maldives
Member since Sun, Feb 27, 2022
2 Years ago
maurodannyr questions
Fri, Jul 9, 21, 00:00, 3 Years ago
Thu, Sep 17, 20, 00:00, 4 Years ago
Sat, Sep 28, 19, 00:00, 5 Years ago
;