I have the following yup check:
JavaScript
x
2
1
nrOfApples: yup.number().min(0).max(999),
2
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:
JavaScript
1
2
1
yup.number().nullable()
2
But it doesn’t seem to work. Any ideas on how I can make such thing happen?
Advertisement
Answer
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:
JavaScript
1
12
12
1
const contactSchema = yup.object({
2
name: yup.string()
3
.required(),
4
nrOfApples: yup
5
.number()
6
.min(0)
7
.max(999)
8
.nullable(true)
9
// checking self-equality works for NaN, transforming it to null
10
.transform((_, val) => val === Number(val) ? val : null)
11
})
12