Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a yup number accept nullable values?

Tags:

javascript

yup

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?

like image 516
manzk Avatar asked Aug 03 '20 13:08

manzk


People also ask

Can mandatory field be null?

Further more , you can't insert null values into mandatory fields. You can update other fields as null. In data loader insert null comes into picture when you insert a csv with empty cells for some field which is not mandatory. Generally data loader won't let you insert null values to any field.

How do you validate field only exists?

You can set a additional boolean key where value is default false. Change it to true when you modify the value in step 1. And then if the value is true for that key then apply the validation.

What is schema in Yup?

Yup is a JavaScript schema builder for value parsing and validation. Define a schema, transform a value to match, validate the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformations.

What is shape in Yup?

yupobject documentation. Basically passing the schema to shape is just the long-form of passing it to the object constructor. Shape does however offer the benefit of chaining and overloading definitions in later chained methods. See yup.shape documentation. Follow this answer to receive notifications.


1 Answers

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) 
})
like image 100
xdumaine Avatar answered Oct 08 '22 07:10

xdumaine