Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yup how to validate mandatory fields on null object

I have a problem regarding the validation of mandatory fields which are properties of a (possibly) null object.

Here is an example schema :

object().shape({
   catalog: {
      brand: string().required()
   }
})

If I try to validate the following object against this schema, I get the expected error : brand is required. From what I understood, there is a default value created for undefined object which mimics the shape of the object in the schema. This is the behavior I expected and what I want.

{ catalog: undefined }

// "catalog.brand is a required field"

But in my case, I don't receive an object with undefined, but with null. And I can't figure out how to manage the same result with a null value.

{ catalog: null }

// No error on catalog.brand

Manually casting null to undefined is out of the question as there is a good reason why I receive null.

Here is a codesandbox which reproduces my use case :

https://codesandbox.io/s/yup-playground-tbfcj

I would really appreciate a bit of help on this, thanks :)

like image 748
Orodan Avatar asked Oct 20 '25 15:10

Orodan


2 Answers

The solution is to include both nullable() and required() to the shape.

Example

const requiredOption = Yup.object()
  .shape({
    value: Yup.string(),
    label: Yup.string(),
  })
  .nullable()
  .required('This field is required.');
like image 66
Deepak Kadarivel Avatar answered Oct 22 '25 05:10

Deepak Kadarivel


Try adding strict() on your object schema

object().shape({
   catalog: {
      brand: string().required()
   }
}).strict();
like image 20
Amedeo Zucchetti Avatar answered Oct 22 '25 05:10

Amedeo Zucchetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!