talyssonoc / structure

A simple schema/attributes library built on top of modern JavaScript
https://structure.js.org/
MIT License
301 stars 20 forks source link

Question: How to validate object keys? #160

Open ethimjos-velo opened 3 years ago

ethimjos-velo commented 3 years ago

I have a case where I need to validate the structure of an object, which in turn can also contain keys that are objects. The structure is like this:

const test = {
    firstname : "TestName",        // Required
    lastname  : {                  // Required
        paternal : "TestPaternal", // Required
        maternal : "TestMaternal"  // Required
    }
};

To validate the structure of the object I've written something like below but the paternal and maternal keys are not validated. You can pretty much put whatever you want inside this object.

const Schema = attributes( {
    firstname : {                                  // Validated OK
        type     : String,
        required : true
    },
    lastname  : {                                  // Validated OK in the sense that the value for this key should be an object and not missing as key, but the keys of the object itself are not validated.
        type       : Object,
        required   : true,
        attributes : {
            paternal : {                           // Not Validated
                type     : String,
                required : true
            },
            maternal : {                           // Not Validated
                type     : String,
                required : true
            },
        }
    }
} )( class Person {} );

Even if I change it to something like this it still won't work.

const Schema = attributes( {
    firstname : {                                  // Validated OK
        type     : String,
        required : true
    },
    lastname  : {                                  // Validated OK in the sense that the value for this key should be an object and not missing as key, but the keys of the object itself are not validated.
        type       : Object,
        required   : true,
        paternal : {                               // Not Validated
            type     : String,
            required : true
        },
        maternal : {                               // Not Validated
            type     : String,
            required : true
        },
    }
} )( class Person {} );

Any suggestion on how can I achive this? Thank you!