Last active
January 17, 2016 19:51
-
-
Save MarkHerhold/795cc1f73065ca2f3b76 to your computer and use it in GitHub Desktop.
Nested noChange() Joi Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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