【问题标题】:Can I still use express-validator even if there is no concept of email?即使没有电子邮件的概念,我还能使用 express-validator 吗?
【发布时间】:2020-07-22 04:51:57
【问题描述】:

所以我正在使用 TypeScript 在 Express 中开发一个注册路由处理程序。我使用express-validators 来避免我必须在路由处理程序中写出的所有这些代码,但是在我快速浏览的文档中,我没有看到username 的示例,只有email 的示例。任何有更多经验的人都知道我是否可以仅对passwordpasswordConfirmation 实施验证,对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 相同的环境中工作吗?

【问题讨论】:

    标签: typescript express express-validator


    【解决方案1】:

    您可以使用 oneOf 并通过传递验证链来验证用户名和电子邮件。 用例子检查文档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 });
        });
    
    

    【讨论】:

    • 谢谢。在文档中完全错过了这一点。
    猜你喜欢
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2011-10-09
    • 2020-12-27
    • 1970-01-01
    • 2022-10-14
    • 2011-12-22
    相关资源
    最近更新 更多