Configuration Object

Once we have defined all our Joi specs, its time to configure our middleware. Following is a high-level schema of configuration object expected by xpress-req-validator

{
    allowUndefinedPaths: true,
    sendErrorResponse: false,
    specs: {
        GET: {},
        POST: {},
        PUT: {},
        DELETE: {},
    },
}

allowUndefinedPaths

if set to true, middleware will allow undefined routes to pass through

if set to false, middleware will raise an INVALID URL error

default is true

sendErrorResponse

if set to true, middleware will send responses directly with validation errors

if set to false, middleware will pass the validation errors to next middleware

default is false

Error response takes the following shape

{
    description: 'request body params validation failed',
    errors: [
        {
            message: '"username" must only contain alpha-numeric characters',
            path: ['username'],
            context: {
                value: 'John Doe',
                key: 'username',
                label: 'username',
            },
        },
        {
            message: '"password" is required',
            path: ['password'],
            context: {
                key: 'password',
                label: 'password',
            },
        },
        {
            message: '"birthyear" is required',
            path: ['birthyear'],
            context: {
                key: 'birthyear',
                label: 'birthyear',
            },
        },
    ],
}

Last updated

Was this helpful?