structure icon indicating copy to clipboard operation
structure copied to clipboard

Question: How to validate object keys?

Open ethimjos-velo opened this issue 4 years ago • 0 comments

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!

ethimjos-velo avatar Nov 15 '21 12:11 ethimjos-velo