ansman / validate.js

A declarative validation library written javascript
https://validatejs.org
MIT License
2.62k stars 337 forks source link

restrict properties #223

Open retorquere opened 7 years ago

retorquere commented 7 years ago

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.

cspotcode commented 7 years ago

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']
ansman commented 6 years ago

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