zaggino / z-schema

JSON Schema validator written in JavaScript for NodeJS and Browsers
Other
340 stars 91 forks source link

Custom formats function #155

Open simon-p-r opened 8 years ago

simon-p-r commented 8 years ago

Hi @zaggino

I am wondering whether you would consider expose the parent object context in the custom format functions. For brevity a simple pseudo example

Schema

        type: 'object',
        properties: {
            buildingNumber: {
                type: 'string'
            },
            county: {
                type: 'string',
                format: 'lookup' 
            }
        },
        required: ['buildingNumber', 'county'],
        additionalProperties: false

lookup format function

lookup: function (child, parent) {

     var type = Object.keys(parent);
     if (lookup[type].indexOf(child) !== -1) {
        return true;
     }
     return false;
}

The lookup object used in function is something like this

{
    county: [
        'essex',
        'middlesex',
        'hampshire'
    ],
    salutation: [
        'mr',
        'mrs'
        'miss'
    ]
}

Data that passes validation

{
    "buildingName": "The Spinneys",
    "county": "essex"
}

Data that fails validation

{
    "buildingName": "The Spinneys",
    "county": "ohio"
}
zaggino commented 8 years ago

Why instead of using format lookup under county you don't put it directly on object and check that like this? It makes more sense to put format there since it relies on properties of the object. The thing you're proposing is not a good approach.

type: 'object',
        properties: {
            buildingNumber: {
                type: 'string'
            },
            county: {
                type: 'string' 
            }
        },
        required: ['buildingNumber', 'county'],
        format: 'lookup',
        additionalProperties: false
simon-p-r commented 8 years ago

That was probably not a good example, basically at that level of object a key would determine how that other keys of object are validated. This proposal for v5 of json schema is something similar to what I am requesting.