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