Skip to content

Validation with custom followed by withMessage always uses thrown message. #1047

@JHawkley

Description

@JHawkley

Describe the bug

There seems to be a regression of #203 from the v2 days or the documentation for withMessage is incorrect.

If you try to override the default message of a custom validator using withMessage, it ignores the provided message.

According to the documentation of withMessage:

.withMessage(message)
Sets the error message for the previous validator.
This will have precedence over errors thrown by a custom validator.

And, according to the Dynamic Messages guide:

If you're using a custom validator, then it may very well throw or reject promises to indicate an invalid value.
In these cases, the error gets reported with a message that's equal to what was thrown by the validator:

...which a colleague initially read as it will always use the message from the error. So, we're not sure which it is supposed to be and it's been so long since #203 that it's hard to say if the intended behavior had been altered since then.

But having withMessage override a default error message from a custom validator to provide better context is a handy tool to have in a validation library.

To Reproduce

A partial reproduction:

const { body, validationResult } = require('express-validator');

const customValidation = () => {
  throw new Error("default message");
};

router.post("/test", [
  body("someValue")
    .custom(customValidation).withMessage("custom message"),
  (req, res) => {
    try {
      validationResult(req).throw();
      res.send("OK");
    }
    catch (err) {
      // Expect to find "default message" in the output for `someValue`.
      console.log(err.mapped());
      res.status(400).send("FAIL");
    }
  }
]);

Expected behavior

I would like it to use the custom error message provided by withMessage
...or the documentation updated to be more clear about how custom validator error messages are intended to be presented.

Current behavior

Always uses the thrown error message; checked in code for src/context-items/custom-validation.js and it indeed preferentially uses err.message or err over this.message when catching an exception from the custom validator.

Express-validator version:

  • Version: Discovered on 6.10.1, verified that it still affects 6.11.1

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions