yup.object().required() works fine - but adding a shape leads to always pass

See original GitHub issue

Hello,

I got this object:

{
  group: {
    id: 1
  }
}

If I validate the field using

Yup.object ().required ()

it works fine and returns an error once group is not set.

If I add

Yup.object ().shape({id: Yup.number().required()}).required ()

the test always passes and does not trigger anything, even if there is no object at all (null).

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:7

github_iconTop GitHub Comments

9reactions
yarapolanacommented, Nov 17, 2022

I can confirm that doing what @Zerebokep said works perfectly. Here is how to do it:

user: yup
    .object()
    .shape({
      name: yup.string().required(),
      avatarUrl: yup.string().required(),
    })
    .default(undefined) // 👈 
    .required(),
3reactions
Zerebokepcommented, Aug 19, 2022

I face the same issue.

edit: using .default(undefined) on the required object fixed my issue, objects default to {}, which is the reason why .required doesn’t throw a validation error.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to assign object validation in yup for react-select (single ...
I want to know how to assign objects in validation schema for yup concept. You did it correct (as far as I can...
Read more >
Validating Optional Objects with Yup - Object Partners
First, notRequired simply makes is so that undefined values do not fail validation. In the case of object types, Yup has a default...
Read more >
React Form Validation With Formik And Yup
We define the shape of the validation object schema and pass it into Yup's shape() method. The required() method. This method takes a...
Read more >
How to Create an Optional Dynamic Validation Schema based ...
We'll setup a basic yup.object() and run isValidSync() and pass in our this.state . The yup.object doesn't have any schema validations so valid...
Read more >
yup - npm.io
Returns true when the passed in value matches the schema. isValid is asynchronous and returns a Promise object. Takes the same options as...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found