Last active
September 27, 2017 18:08
-
-
Save busypeoples/956d56c6ce953c845fd443741e514850 to your computer and use it in GitHub Desktop.
Validate deeply nested inputs.
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
const R = require('ramda') | |
const colors = ['green', 'blue', 'red'] | |
const notEmpty = R.compose(R.not, R.isEmpty) | |
const minLength = a => b => R.length(b) > a | |
const hasPresetColors = x => R.indexOf(x, colors) !== -1 | |
const input = { | |
id: 1, | |
userName: 'Random', | |
address: { | |
street: 'Foobar', | |
}, | |
settings: { | |
profile: { | |
design: { | |
color: 'green', | |
background: 'blue', | |
}, | |
}, | |
}, | |
} | |
const spec = { | |
id: notEmpty, | |
userName: R.allPass([notEmpty, minLength(5)]), | |
address: { | |
street: notEmpty, | |
}, | |
settings: { | |
profile: { | |
design: { | |
color: R.allPass([notEmpty, hasPresetColors]), | |
background: R.allPass([notEmpty, hasPresetColors]), | |
}, | |
}, | |
}, | |
} | |
const result = R.evolve(spec, input) | |
// | |
// result: | |
// { | |
// "id": true, | |
// "userName": true, | |
// " address": { | |
// "street": true | |
// }, | |
// "settings": { | |
// "profile": { | |
// "design": { | |
// "color": true, | |
// "background": true | |
// } | |
// } | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can this be enhanced to support error messages in case of failed validation(s)?