- Notifications
You must be signed in to change notification settings - Fork64
A joi validation middleware for Express.
License
arb/celebrate
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
celebrate is an express middleware function that wraps thejoi validation library. This allows you to use this middleware in any single route, or globally, and ensure that all of your inputs are correct before any handler function. The middleware allows you to validatereq.params
,req.headers
, andreq.query
.
The middleware will also validate:
req.body
— provided you are usingbody-parser
req.cookies
— provided you are usingcookie-parser
req.signedCookies
— provided you are usingcookie-parser
celebrate lists joi as a formal dependency. This means that celebrate will always use a predictable, known version of joi during the validation and compilation steps. There are two reasons for this:
- To ensure that celebrate can always use the latest version of joi as soon as it's published
- So that celebrate can export the version of joi it uses to the consumer to maximize compatibility
celebrate is tested and has full compatibility with express 4 and 5. It likely works correctly with express 3, but including it in the test matrix was more trouble than it's worth. This is primarily because express 3 exposes route parameters as an array rather than an object.
Example of using celebrate on a single POST route to validatereq.body
.
constexpress=require('express');constBodyParser=require('body-parser');const{ celebrate, Joi, errors, Segments}=require('celebrate');constapp=express();app.use(BodyParser.json());app.post('/signup',celebrate({[Segments.BODY]:Joi.object().keys({name:Joi.string().required(),age:Joi.number().integer(),role:Joi.string().default('admin')}),[Segments.QUERY]:{token:Joi.string().token().required()}}),(req,res)=>{// At this point, req.body has been validated and// req.body.role is equal to req.body.role if provided in the POST or set to 'admin' by joi});app.use(errors());
Example of using celebrate to validate all incoming requests to ensure thetoken
header is present and matches the supplied regular expression.
constexpress=require('express');const{ celebrate, Joi, errors, Segments}=require('celebrate');constapp=express();// validate all incoming request headers for the token header// if missing or not the correct format, respond with an errorapp.use(celebrate({[Segments.HEADERS]:Joi.object({token:Joi.string().required().regex(/abc\d{3}/)}).unknown()}));app.get('/',(req,res)=>{res.send('hello world');});app.get('/foo',(req,res)=>{res.send('a foo request');});app.use(errors());
celebrate does not have a default export. The following methods encompass the public API.
Returns afunction
with the middleware signature ((req, res, next)
).
requestRules
- anobject
wherekey
can be one of the values fromSegments
and thevalue
is ajoi validation schema. Only the keys specified will be validated against the incoming request object. If you omit a key, that part of thereq
object will not be validated. A schema must contain at least one valid key.[joiOpts]
- optionalobject
containing joioptions that are passed directly into thevalidate
function. Defaults to{ warnings: true }
.[opts]
- an optionalobject
with the following keys. Defaults to{}
.reqContext
-bool
value that instructs joi to use the incomingreq
object as thecontext
value during joi validation. If set, this will trump the value ofjoiOptions.context
. This is useful if you want to validate part of the request object against another part of the request object. See the tests for more details.mode
- optionalModes
for controlling the validation mode celebrate uses. Defaults topartial
.
This is a curried version ofcelebrate
. It is curried withlodash.curryRight
so it can be called in all the various fashions thatAPI supports. Returns afunction
with the middleware signature ((req, res, next)
).
[opts]
- an optionalobject
with the following keys. Defaults to{}
.reqContext
-bool
value that instructs joi to use the incomingreq
object as thecontext
value during joi validation. If set, this will trump the value ofjoiOptions.context
. This is useful if you want to validate part of the request object against another part of the request object. See the tests for more details.mode
- optionalModes
for controlling the validation mode celebrate uses. Defaults topartial
.
[joiOpts]
- optionalobject
containing joioptions that are passed directly into thevalidate
function. Defaults to{ warnings: true }
.requestRules
- anobject
wherekey
can be one of the values fromSegments
and thevalue
is ajoi validation schema. Only the keys specified will be validated against the incoming request object. If you omit a key, that part of thereq
object will not be validated. A schema must contain at least one valid key.
Sample usage
This is an example use of curried celebrate in a real server.
constexpress=require('express');const{ celebrator, Joi, errors, Segments}=require('celebrate');constapp=express();// now every instance of `celebrate` will use these same options so you only// need to do it once.constcelebrate=celebrator({reqContext:true},{convert:true});// validate all incoming request headers for the token header// if missing or not the correct format, respond with an errorapp.use(celebrate({[Segments.HEADERS]:Joi.object({token:Joi.string().required().regex(/abc\d{3}/)}).unknown()}));app.get('/',celebrate({[Segments.HEADERS]:Joi.object({name:Joi.string().required()})}),(req,res)=>{res.send('hello world');});app.use(errors());
Here are some examples of other ways to callcelebrator
constopts={reqContext:true};constjoiOpts={convert:true};constschema={[Segments.HEADERS]:Joi.object({name:Joi.string().required()})};letc=celebrator(opts)(joiOpts)(schema);c=celebrator(opts,joiOpts)(schema);c=celebrator(opts)(joiOpts,schema);c=celebrator(opts,joiOpts,schema);// c would function the same in all of these cases.
Returns afunction
with the error handler signature ((err, req, res, next)
). This should be placed with any other error handling middleware to catch celebrate errors. If the incomingerr
object is an error originating from celebrate,errors()
will respond a pre-build error object. Otherwise, it will callnext(err)
and will pass the error along and will need to be processed by another error handler.
[opts]
- an optionalobject
with the following keysstatusCode
-number
that will be used for the response status code in the event of an error. Must be greater than 399 and less than 600. It must also be a number available to the nodeHTTP module. Defaults to 400.message
-string
that will be used for themessage
value sent out by the error handler. Defaults to'Validation failed'
If the error response format does not suite your needs, you are encouraged to write your own and checkisCelebrateError(err)
to format celebrate errors to your liking.
Errors origintating from thecelebrate()
middleware areCelebrateError
objects.
celebrate exports the version of joi it is using internally. For maximum compatibility, you should use this version when creating schemas used with celebrate.
An enum containing all the segments ofreq
objects that celebratecan validate against.
{BODY:'body',COOKIES:'cookies',HEADERS:'headers',PARAMS:'params',QUERY:'query',SIGNEDCOOKIES:'signedCookies',}
An enum containing all the available validation modes that celebrate can support.
PARTIAL
- ends validation on the first failure. Doesnot apply joi transformations if any part of the request is invalid.FULL
- validates the entire request object and collects all the validation failures in the result. Doesnot apply joi transformations if any part of the request is invalid.- Note: In order for this to work, you will need to pass
abortEarly: false
to#joiOptions. Or to get the default behavior along with this,{ abortEarly: false, warnings: true }
- Note: In order for this to work, you will need to pass
Creates a newCelebrateError
object. Extends the built inError
object.
message
- optionalstring
message. Defaults to'Validation failed'
.[opts]
- optionalobject
with the following keyscelebrated
-bool
that, whentrue
, addsSymbol('celebrated'): true
to the result object. This indicates this error as originating fromcelebrate
. You'd likely want to set this totrue
if you want the celebrate error handler to handle errors originating from theformat
function that you call in user-land code. Defaults tofalse
.
CelebrateError
has the following public properties:
details
- aMap
of all validation failures. Thekey
is aSegments
and the value is a joi validation error. Adding todetails
is done viadetails.set
. Thevalue
must be a joi validation error or an exception will be thrown.
Sample usage
constresult=Joi.validate(req.params.id,Joi.string().valid('foo'),{abortEarly:false});consterr=newCelebrateError(undefined,{celebrated:true});err.details.set(Segments.PARAMS,result.error);
Returnstrue
if the providederr
object originated from thecelebrate
middleware, andfalse
otherwise. Useful if you want to write your own error handler for celebrate errors.
err
- an error object
celebrate validates request values in the following order:
req.headers
req.params
req.query
req.cookies
(assumingcookie-parser
is being used)req.signedCookies
(assumingcookie-parser
is being used)req.body
(assumingbody-parser
is being used)
If you use any of joi's updating validation APIs (default
,rename
, etc.)celebrate
will override the source value with the changes applied by joi (assuming the request is valid).
For example, if you validatereq.query
and have adefault
value in your joi schema, if the incomingreq.query
is missing a value for default, during validationcelebrate
will overwrite the originalreq.query
with the result ofjoi.validate
. This is done so that oncereq
has been validated, you can be sure all the inputs are valid and ready to consume in your handler functions and you don't need to re-write all your handlers to look for the query values inres.locals.*
.
According the the HTTP spec,GET
requests shouldnot include a body in the request payload. For that reason,celebrate
does not validate the body onGET
requests.
Before opening issues on this repo, make sure your joi schema is correct and working as you intended. The bulk of this code is just exposing the joi API as express middleware. All of the heavy lifting still happens inside joi. You can gohere to verify your joi schema easily.
About
A joi validation middleware for Express.