Skip to content

Optional flag not working for sub-schemas #475

@vpalos

Description

@vpalos

In version 3.4.0 of the package, setting optional: true on an object property which has its own required sub-fields, will enforce the object's sub-fields as required, even if the entire object is missing (which should be allowed, since the object itself is marked as optional).

See example below:

const addressSchema = new Schema({
    city: String,
});

const schema = new Schema({
    name: String,
    homeAddress: addressSchema,
    billingAddress: {
        type: addressSchema,
        optional: true,
    },
});

const context = schema.newContext();
context.validate({
  // EMPTY OBJECT
});

console.error(context.validationErrors());

The console output will show these errors:

0:{name: 'name', type: 'required', value: undefined} // OK
1:{name: 'homeAddress', type: 'required', value: undefined} // OK
2:{name: 'homeAddress.city', type: 'required', value: undefined} // OK
3:{name: 'billingAddress.city', type: 'required', value: undefined} // THIS IS WRONG!!!

Expected behavior:
The last error should not happen, of course because the entire billingAddress object is set as optional: true, therefore it's internal properties should only be enforced if (and only if) the object exists in the first place.

This expected behavior is also described in the documentation: https://github.com/longshotlabs/simpl-schema#optional

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions