Handle default values in object schemas
masterObject schemas can provide default values for their fields using .default(). Calling .default() on the schema itself builds out the object shape and fills in all defaults for the entire nested structure.
Warning on Nested Objects: If a nested object is optional but contains non-optional fields, validation might fail unexpectedly because Yup casts the input before validating. To avoid this, either set the nested default to undefined or mark it as nullable() and default to null.
let schema = object({
name: string().default(''),
});
schema.default(); // -> { name: '' }
// To avoid unexpected validation failures in nested objects:
let safeSchema = object({
id: string().required(),
names: object({
first: string().required(),
}).default(undefined), // Option 1: Set default to undefined
// OR
// names: object({ first: string().required() }).nullable().default(null), // Option 2
});