Yup: How to create optional object with required fields?

Created on 5 Feb 2020  路  8Comments  路  Source: jquense/yup

Hi, is it possible to create the following schema:

yup.object({
  foo: yup.object({
    bar: yup.string().required()
  })
})

where you can either provide foo or not, but if you do, you must provide bar? Running the above schema on {}, I'm getting foo.bar is required

Most helpful comment

Objects automatically default there fields which is why its complaining. If you want the object to be optional and empty by default set .default() to null or undefined on the foo object schema

All 8 comments

Objects automatically default there fields which is why its complaining. If you want the object to be optional and empty by default set .default() to null or undefined on the foo object schema

Objects automatically default there fields which is why its complaining. If you want the object to be optional and empty by default set .default() to null or undefined on the foo object schema

No longer works.

please provide a repro, drive-by comments on closed issues aren't helpful and aren't likely to get something fixed

please provide a repro, drive-by comments on closed issues aren't helpful and aren't likely to get something fixed

Right. Apologies.

Edit upbeat-wood-3i50n

@cgarrovillo i'm not sure what you are expecting here? You are providing an initial value for optional so it doesn't matter what default you set, it's not used. defaults are used when the field is undefined.

@jquense I am having a similar issue with @cgarrovillo. What I am trying to do is to define an object like this:

interface Child {
  name: string;
}
interface Parent {
  child?: Child
}

The child field is optional. But if it is present, it has to have the field name.

const parent = object({ child: object({ name: string.required() }).default(undefined) })

Thanks you for your quick response. It works!

Was this page helpful?
0 / 5 - 0 ratings