validate.js icon indicating copy to clipboard operation
validate.js copied to clipboard

restrict properties

Open retorquere opened this issue 8 years ago • 2 comments
trafficstars

Is it possible to have the validation restrict properties? I not only want to validate properties I know about but also make sure no properties get in that I don't already know about.

retorquere avatar Sep 02 '17 18:09 retorquere

You can write a custom validator in a couple lines that implements property whitelisting. Usage will look strange since you'll have to associate it with a non-existent property, but it should work regardless.

validate.validators.restrictProperties = function(value, options, attribute, attributes, globalOptions) {
    const unexpectedProperties = Object.keys(attributes).filter(prop => options.whitelist.indexOf(prop) === -1);
    if(unexpectedProperties.length) return options.message || `^Attributes object has unexpected properties: ${ unexpectedProperties.join(', ') }`;
};

validate({a: 1, b: 2, c: 3, d: 4}, {
    // normal validations here
    // Whitelist properties
    nonexistent: {
        restrictProperties: {
            whitelist: ["a", "c"]
        }
    }
}, {format: 'flat'});
// ['Unexpected properties: b, d']

cspotcode avatar Sep 09 '17 00:09 cspotcode

There isn't, but perhaps there should be something like this. You can clean data using cleanAttributes function but this would be useful too.

ansman avatar Nov 12 '17 04:11 ansman