validate.js
validate.js copied to clipboard
restrict properties
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.
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']
There isn't, but perhaps there should be something like this. You can clean data using cleanAttributes function but this would be useful too.