To validate an object with Yup so that it can either be an object or null, you can use the .nullable() method in combination with the .shape() method. This allows you to define the object's shape (properties and their validation rules) and also accept null as a valid value for the object.

Here's an example of how you can achieve this:

javascript
import * as Yup from 'yup'; // Define the shape of the object with validation rules const objectShapeSchema = Yup.object().shape({ name: Yup.string().required('Name is required'), age: Yup.number().integer().positive().required('Age is required'), // Add more properties and validation rules as needed }); // Define the schema for the main object (can be either an object or null) const mainSchema = Yup.mixed().nullable().when( // The field you want to validate (in this case, the main object) 'fieldName', { // Validation logic is: (value) => value !== null, then: objectShapeSchema, // If not null, apply the object shape schema otherwise: Yup.object().nullable(), // If null, treat it as a valid value } ); // Example usage const data1 = { fieldName: { name: 'John', age: 30, }, }; const data2 = { fieldName: null, }; const data3 = { // 'fieldName' is missing, treated as null }; // Validate the data against the main schema mainSchema.validate(data1) .then((validatedData) => console.log('Data 1:', validatedData)) .catch((error) => console.error('Data 1 validation error:', error)); mainSchema.validate(data2) .then((validatedData) => console.log('Data 2:', validatedData)) .catch((error) => console.error('Data 2 validation error:', error)); mainSchema.validate(data3) .then((validatedData) => console.log('Data 3:', validatedData)) .catch((error) => console.error('Data 3 validation error:', error));

In the above example, we first define the objectShapeSchema to represent the shape of the object with its validation rules. Then, we define the mainSchema, which uses .when() to conditionally apply the objectShapeSchema based on the value of the field named 'fieldName'. If 'fieldName' is not null, the objectShapeSchema will be applied; otherwise, mainSchema will treat the object as valid, allowing null values.

Keep in mind that you can modify the validation rules in objectShapeSchema and the name of the field you want to conditionally validate based on your specific use case.

Have questions or queries?
Get in Touch