simonplend / express-json-validator-middleware

Express middleware for validating requests against JSON schema

Home Page:https://npm.im/express-json-validator-middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to add custom errors to?

ANorseDude opened this issue · comments

Hi,

I've been trying for a while to setup so I can post a custom errormessage ith the validationErrors but I can't seem to get it to work. I'm not sure what I'm doing wrong. Is there any examples of this?

Import everything;

const { Validator } = require('express-json-validator-middleware');
const { validate } = new Validator();

Create the scheme to validate against,

exports.test = {
	type: 'object',
	required: ['name'],
	properties: {
		name: {
			type: 'string',
		},
	},
	errorMessage: 'This is the message I want to pass on and overwrite the standard one..',
};

Set it up as a middleware
router.get('/test', validate({ body: userValidator.test }), userController.test);

And this is the response,

"error": {
    "name": "JsonSchemaValidationError",
    "validationErrors": {
      "body": [
        {
          "keyword": "required",
          "dataPath": "",
          "schemaPath": "#/required",
          "params": {
            "missingProperty": "name"
          },
          "message": "should have required property 'name'"
        }
      ]
    },

I tried following this: https://github.com/simonplend/express-json-validator-middleware#ajv-instance, but that didn't solve it (honestly the ajv-instance just crashes the server.

Running a node server (v14.15.4), with express(v4.17.1)

Most likely I'm missing out some really basic part but an anyone help me out with how to get this package working with a custom errormessage?

Thanks in advance!

Have you figured it out?

I've done some researches I'm afraid in order to do this we need https://github.com/ajv-validator/ajv-errors but it depends on ajv@^8 while express-json-validator-middleware depends on ajv@^6.6.2

So I guess the best way at the moment is to add another middleware (in your express application) and do validation manually. From there you can throw a ValidationError (or any other error) with the message you want to show, like so:

router.post(
  '/test',
  validate({ // AJV validation
    body: {
      type: 'array',
      items: {
        type: 'string',
      },
      minItems: 1,
      uniqueItems: true,
    },
  }),
  (req, res, next) => { // Manual validation
    req.body.forEach((item, i) => {
      if (!isValid(item)) {
        throw new ValidationError({
          body: [{
            keyword: 'format',
            dataPath: `[${i}]`,
            schemaPath: '#/items/format',
            params: {
              format: 'test_format',
            },
            message: `${item} is invalid`,
          }],
        });
      }
    });

    next();
  },
);

There are two approaches you can take: