express-validator: checkSchema - custom validator and exists errorMessage

Hi!

I’m trying to use Schema Validation with 5.0.0.

  1. custom validator throw validation error validatorCfg.validator is not a function
  2. For exists param errorMessage ignored
checkSchema({
  title: {
    in: ['body'],
    exists: {
      errorMessage: 'title is required', // <- doesn't work
    },
    custom(value) { // <- doesn't work
      console.log(value);
      return true;
    }
  },
  password: {
    isLength: {
      errorMessage: 'Password should be at least 7 chars long', // <- works
    },
  },
});

customValidators param and all in this doc section https://github.com/ctavan/express-validator#legacy-api are deprecated…

What am I doing wrong?

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 17 (8 by maintainers)

Most upvoted comments

Hm, the exists one is strange, by “doesn’t work” do you mean the error message is still Invalid value? It shouldn’t be, so there might be something else wrong with your setup.

The custom one should be specified by passing options. I will add an example to help clear future questions about it.

This is a very minimal app with both validators working:

const { checkSchema, validationResult } = require('./check');

const express = require('express');
const app = express();
app.use(express.json());
app.post('/*', checkSchema({
  foo: {
    in: ['body'],
    exists: {
      errorMessage: 'bla'
    },
    custom: {
      options: value => (value || '').startsWith('foo')
    }
  }
}), (req, res) => {
  res.json(validationResult(req).array());
});

app.listen(3000);

Hi @prettymuchbryce, it’s out of the plans for the check APIs to have any interactions with the legacy ones (the expressValidator middleware you used), as they are gonna be phased out at some point. The less state we store in the request, the better.

What I would like to do instead is something like validatorResult.withDefaults(options): a factory for the check API that you can inject custom defaults, like validators:

// Use these, don't import them from `express-validator/check`!
const { check, checkSchema, validationResult, etc } = createCheckAPI({
  customSanitizers: { ... },
  customValidators: { ... },
  someOtherOption: value
})

For now, what you can do is move these validators or schemas (or whatever you like) into separate files, and import them in your schemas.

Yes, the same for custom sanitizers.