Note: This is the core version of adhere. It contains only the essentials making it easy to understand what adhere does.
Check out the common version of adhere. It contains functions your are likely to need in your projects.
var post = {
id: '1234abcd',
title: 'My Summer Adventures',
tag: 1
};
var validator = adhere({
title: coerceString,
tag: [coerceString, expectTag]
});
validator(post);
function expectTag(string) {
if (!/[a-z0-1]+/.test(string)) throw Exception('Invalid tag.')
return string
}
function coerceString(value) {
return '' + value
}
Adhere accepts transforms which are just functions of the form:
function identity(value, key, obj) {
return value
}
This means you can normalize your data by returning a different value. To filter erroneous data I recommend to throw exceptions from your transforms. For example:
function expectObject(value, key, obj) {
if (Object.prototype.toString.call(value) !== '[object Object'])
throw new Error('Expected an object')
return value
}