Skip to content

Instantly share code, notes, and snippets.

@MarkHerhold
Last active January 17, 2016 19:51
Show Gist options
  • Save MarkHerhold/795cc1f73065ca2f3b76 to your computer and use it in GitHub Desktop.
Save MarkHerhold/795cc1f73065ca2f3b76 to your computer and use it in GitHub Desktop.
Nested noChange() Joi Validation
var validate = require('json-patch-joi');
var Joi = require('joi');
function clone(obj) { return JSON.parse(JSON.stringify(obj)); }
// original object to be patched
let obj = { nested: { stuff: true } };
// patch that illegally modifies the stuff value
const patch = [{
op: 'replace',
path: '/nested/stuff',
value: 'something else'
}];
// With the use of "noChange()", validating bad patches is easy
const schema = Joi.object().keys({
nested: Joi.object().keys({
stuff: Joi.any().noChange(obj)
})
});
// Joi validation error object in res.error
const res = validate(clone(obj), schema, patch);
// `res.error.message`: child "nested" fails because [child "stuff" fails because ["stuff" is not allowed to be changed]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment