自定义验证仅适用于架构验证[express-validator]

时间:2018-10-31 12:50:00

标签: javascript node.js typescript express express-validator

我试图定义一个自定义函数来验证一种形式的字段。我注意到该功能仅在通过架构执行验证时才有效。没有办法也可以在链验证中工作吗?

validation.js

    export = {
  customValidators: {
    isUsernameAvailable(username: string) {
      return new Promise((resolve, reject) => {
        User.findOne({ username: username }, (err, user) => {
          if (err) throw err;
          if (user == null) {
            resolve();
          } else {
            reject();
          }
        });
      });
    }
  }
};

app.js

app.use(expressValidator(require("./validation")));

这不起作用:

router.post(
  "/",
  [
    checkBody("username").isUsernameAvailable()
  ],
  (req, res) => {
    const err = validationResult(req);
    if (err) return res.json(err);
    res.json({ success: true });
  }
);

这有效:

router.post("/", async (req, res) => {
  req.checkBody({
    //username
    username: {
      notEmpty: true,
      isUsernameAvailable: {
        errorMessage: "username is already taken"
      },
    },
    //password
    password: {
      notEmpty: true,
    }
  });
  try {
    const result = await req.asyncValidationErrors();
  } catch (err) {
    res.status(400).json(err);
  }
});

0 个答案:

没有答案