Troi is a middleware-based data validation and sanitization library.
npm install troi
const troi = require('troi/chain');
const schema = troi.object({
username: troi.filled()
.string()
.trim()
.lengthBetween(2, 10),
email: troi.filled()
.lowercase()
.email(),
password: troi.filled()
.string()
.lengthBetween(3, 30)
.pattern(/^[a-zA-Z0-9]+$/)
});
schema.validate({
username: 'karate-kid',
email: 'larusso@example.org',
password: 'n0C0br4k4i'
});
// -> { username: 'karate-kid', email: 'larusso@example.org', password: 'N0C0br4k4i' }
schema.validate({
username: 'karate-kid'
});
// Throws validation errorWork in progress
Work in progress
Middleware functions can perform the following tasks:
- return validation errors and stop further execution
- transform values (examples:
trim,nullify) - intercept execution (examples:
optional,nullable)
A middleware function that may transform its input argument and return another value.
const trim = (input, next) => next(typeof input === 'string' ? input.trim() : input);A middleware function that may stop the execution of remaining middleware functions.
const optional = (input, next) => input === undefined ? input : next(input)A function that always returns the same value that was used as its argument.
identity('string') // returns 'string'- Allow middleware to pass
ValidationErrortonext()and stop execution - Make chain builder immutable
- Add
coercetransform function - Rename all
valuearguments toinputfor consistency - Use rollup.js