即使没有电子邮件的概念,我仍然可以使用 express-validator 吗?
Can I still use express-validator even if there is no concept of email?
所以我正在使用 TypeScript 在 Express 中开发注册路由处理程序。我正在使用 express-validators
来避免我必须在我的路由处理程序中写出所有这些代码,但是在我快速浏览过的文档中,我没有看到 username
的示例,只有 email
。任何有更多经验的人都知道我是否可以只对 password
和 passwordConfirmation
实施验证以及对 username
?
实施硬代码验证
这是我目前所拥有的:
import express, { Request, Response } from "express";
import { body } from "express-validator";
const router = express.Router();
router.post(
"/auth/signup",
[
body("password")
.trim()
.isLength({ min: 4, max: 20 })
.withMessage("Must be between 4 and 20 characters"),
body("passwordConfirmation").custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error("Passwords must match");
}
}),
],
(req: Request, res: Response) => {
const { username, password, passwordConfirmation } = req.body;
// const existingUser = await usersRepo.getOneBy({ username });
// if (existingUser) {
// return res.status(422).send({ username: "Username already in use" });
// }
// const user = await usersRepo.create({
// username,
// password,
// passwordConfirmation,
// });
// req.session.userId = user.id;
// res.status(200).send({ username: req.body.username });
}
);
export { router as signupRouter };
当然我知道我在回调前面缺少 async
以使用注释掉的内容。
我注释掉的内容是否可以在与 express-validators
相同的环境中工作?
您可以使用 oneOf 并通过传递 validationChains 来验证用户名和电子邮件。
用例子检查文档 here
查看此示例以获得更多说明
const validation = [
oneOf([
check('useroremail')
.exists()
.withMessage('username is required')
.isLength({ min: 3 })
.withMessage('wrong username length'),
check('useroremail')
.exists()
.withMessage('Email is required')
.isEmail()
.withMessage('Email is not valid'),
]),
check('password')
.exists()
.withMessage('password is required')
];
function ValidationErrors(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(util.inspect(errors.array()));
return res.status(422).json({ errors: errors.array() });
}
next();
};
router
.post('/', validation, ValidationErrors,
(req, res) =>
{
const isEmail = validator.isEmail(req.body.useroremail);
res.status(200).json({ isEmail });
});
</pre>
所以我正在使用 TypeScript 在 Express 中开发注册路由处理程序。我正在使用 express-validators
来避免我必须在我的路由处理程序中写出所有这些代码,但是在我快速浏览过的文档中,我没有看到 username
的示例,只有 email
。任何有更多经验的人都知道我是否可以只对 password
和 passwordConfirmation
实施验证以及对 username
?
这是我目前所拥有的:
import express, { Request, Response } from "express";
import { body } from "express-validator";
const router = express.Router();
router.post(
"/auth/signup",
[
body("password")
.trim()
.isLength({ min: 4, max: 20 })
.withMessage("Must be between 4 and 20 characters"),
body("passwordConfirmation").custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error("Passwords must match");
}
}),
],
(req: Request, res: Response) => {
const { username, password, passwordConfirmation } = req.body;
// const existingUser = await usersRepo.getOneBy({ username });
// if (existingUser) {
// return res.status(422).send({ username: "Username already in use" });
// }
// const user = await usersRepo.create({
// username,
// password,
// passwordConfirmation,
// });
// req.session.userId = user.id;
// res.status(200).send({ username: req.body.username });
}
);
export { router as signupRouter };
当然我知道我在回调前面缺少 async
以使用注释掉的内容。
我注释掉的内容是否可以在与 express-validators
相同的环境中工作?
您可以使用 oneOf 并通过传递 validationChains 来验证用户名和电子邮件。 用例子检查文档 here
查看此示例以获得更多说明
const validation = [
oneOf([
check('useroremail')
.exists()
.withMessage('username is required')
.isLength({ min: 3 })
.withMessage('wrong username length'),
check('useroremail')
.exists()
.withMessage('Email is required')
.isEmail()
.withMessage('Email is not valid'),
]),
check('password')
.exists()
.withMessage('password is required')
];
function ValidationErrors(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(util.inspect(errors.array()));
return res.status(422).json({ errors: errors.array() });
}
next();
};
router
.post('/', validation, ValidationErrors,
(req, res) =>
{
const isEmail = validator.isEmail(req.body.useroremail);
res.status(200).json({ isEmail });
});
</pre>