Skip to content

Instantly share code, notes, and snippets.

@dschnare
Last active October 5, 2019 04:01
Show Gist options
  • Save dschnare/931e94b9474ba60e8733c635b1e2459b to your computer and use it in GitHub Desktop.
Save dschnare/931e94b9474ba60e8733c635b1e2459b to your computer and use it in GitHub Desktop.
Small validation library
function validate (value, validators, message = 'Invalid value') {
validators = [].concat(validators)
if (typeof message !== 'string') {
throw Object.assign(
new Error('Argument "message" must be a string'),
{
name: 'ArgumentError',
propertyName: 'message',
propertyValue: message
}
)
}
if (validators.some(validator => typeof validator !== 'function')) {
throw Object.assign(
new Error('Argument "validators" must be an array of functions'),
{
name: 'ArgumentError',
propertyName: 'validators',
propertyValue: validators
}
)
}
const result = validators.reduce((result, validator) => {
if (!result.success) return result
result = validator(result.value)
if (typeof result !== 'boolean' && Object(result) !== result) {
throw Object.assign(
new Error('Validator function result is invalid'),
{
name: 'ValidationError',
result
}
)
}
return typeof result === 'boolean'
? { value, success: result, message }
: { message, ...result, success: !!result.success }
}, { value, success: true, message })
return result
}
validate.pointer = function validatePointer (jsonPointer, validators, message) {
return obj => {
if (JSONPointer.isJSONPointer(jsonPointer)) {
const value = JSONPointer.get(jsonPointer, obj)
return {
...validate(value, validators, message),
pointer: jsonPointer
}
} else {
throw Object.assign(
new Error('Argument "jsonPointer" is invalid'),
{
name: 'ArgumentError',
propertyName: 'jsonPointer',
propertyValue: jsonPointer
}
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment