modern-express-joi
An express.js middleware makes a powerful validation request with the Joi validation.
Inspiration
express-validator
and Joi validation
Usage
npm install modern-express-joi
import modernValidator from 'modern-express-joi'
orrequire('modern-express-joi').default
- make an
express
middleware from passing schemas tomodernValidator
- add middleware to express
- call
req.checkAny
for validating - call
req.sanitizeAny
for sanitizing
req.checkAny(String, [option])
Passing first params as string to select schema template.
You can pass option
as string for deep checking field by key name.
Here are available commands.
req.checkBody
for validationreq.body
.req.checkQuery
for validationreq.query
.req.checkParams
for validationreq.params
.req.checkHeaderscoming soonreq.checkCookiescoming soon
req.sanitizeAny(String)
This is similar to req.checkAny
about passing params, but it converts the target object such as req.body
, req.query
, req.params
etc to defining format in schemaTemplates
.
modernValidator(Object, [option])
Passing schemaTemplates
as object that has key name of your schema templates to construct an express middleware.
The second optional parameter must be an object that contains functions, and key names are only errorFormatter
, customValidator
, or customSanitizer
.
Example Passing Parameters
errorFormatter(errors)
A function that receives errors array
or false
for formatting errors when using req.validationErrors()
.
customValidator(value)
A function that validates the received value then returns error array
or false
.
customSanitizer(value, schema)
A function that recieves value and schema then returns formatting value follows by schema.
req.validationErrors()
Getting your result of validation after you called req.checkAny
. It returns false
if it has no validation errors, but It returns error array
in otherwise.
Example Simple Validation
// examples/simple-validation.jsconst app = app const template = Joiobjectconst schemaTemplates = template appapp appconsole
Passed
// Request // Response 200
Failed
// Request // Response 400
Example Error Formatter
// examples/error-formatter.jsconst app = app const template = Joiobjectconst schemaTemplates = templateconst errorFormatter = errors appapp appconsole
Example Deep Checking Field
// examples/deep-checking.jsconst app = app const schemaTemplates = templateName: Joi templateAge: Joi appapp appconsole;