Skip to content

Instantly share code, notes, and snippets.

@busypeoples
Last active September 27, 2017 18:08
Show Gist options
  • Save busypeoples/956d56c6ce953c845fd443741e514850 to your computer and use it in GitHub Desktop.
Save busypeoples/956d56c6ce953c845fd443741e514850 to your computer and use it in GitHub Desktop.
Validate deeply nested inputs.
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
// }
// }
// }
// }
@tsawan
Copy link

tsawan commented Sep 3, 2017

Can this be enhanced to support error messages in case of failed validation(s)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment