Home > Blockchain >  Express validator custom function
Express validator custom function

Time:04-01

I'm trying to write a custom validator for an express API. I can't figure out how I can reject incorrect values from the custom validator. Here's what I have:


function validateInput(value) {
    if (!(
        (check(value).isIn(utils.getNames()) ||
        check(value).isIn(utils.getIds()) ||
        check(value).isIn(utils.getHexIds()))
    )) {
        return Promise.reject("Invalid input");
    }
}

router.get('/endpoint',
    query("input").custom(async (value) => {
        await validateInput(value).catch()
    }),
    async (req, res) => {
        try {
            validationResult(req).throw();
        } catch (err) {
            res.status(400).json({"error": "A valid value for input must be passed"});
            return;
        }
   }

I have a feeling I"m not correctly handling the promise correctly, but I can't figure out the right solution either. Here are the docs for the custom validator: https://express-validator.github.io/docs/custom-validators-sanitizers.html

CodePudding user response:

Looks like you are over-complicating the validator.

First, .catch() should take an argument as a general rule.

Here, you do want the promise to reject in case of invalidation, so you don't need to catch.

How about:

query("input").custom(validateInput)
  • Related