簡體   English   中英

express-validator 在有效字段上拋出錯誤

[英]express-validator throw errors on valid fields

我正在使用 express-validator 來驗證 typescript api 中的用戶輸入。 我的驗證鏈:

  export const userValidator = [
  body("email").isEmpty().withMessage("email is required"),
  body("email").isEmail().withMessage("email is not valid"),

  body("username")
    .isEmpty()
    .withMessage("first name has to be longer then 2 charecters"),
  body("username").isLength({ min: 2 }).withMessage("first name is required"),

  body("phoneNum").isNumeric().withMessage("enter a valid phone number"),

  body("password").isEmpty().withMessage("password is required"),
  body("password")
    .isLength({ min: 8 })
    .withMessage("password must be at least 8 characters"),

  body("confiremdPassword").custom((value: string, { req }) => {
    if (value !== req.body.password) {
      throw new Error("password have to match!");
    } else {
      return true;
    }
  }),
];

我正在檢查auth.ts中的錯誤:

 const errors = validationResult(req);
 if (!errors.isEmpty()) {
    const error: ServerError = new Error("Validation failed");
    error.status = 422;
    error.data = errors.array();
    throw error;
 }

但是這樣做的結果很奇怪,因為我毫無理由地得到了一系列所有可能的錯誤......

[

{ value: 'bro1@bro.com', msg: 'email is required', param: 'email', location: 'body' }, { value: 'brrrrrro', msg: '名字必須長於 2 charecters', param: 'username', location: 'body' }, { value: undefined, msg: 'enter a valid phone number', param: 'phoneNum', location: 'body' }, { value: 'brorrrrrrrr' , msg: 'password is required', param: 'password', location: 'body' } ] 你可以看到它甚至告訴我電子郵件是空的,即使它告訴我它的價值。

你必須顛倒你的邏輯。

在您的代碼中,您告訴 express-validator 電子郵件字段必須為空,否則它將視為錯誤。

只需在.isEmpty()驗證器之前添加.not() () 即可。

body("email").not().isEmpty().withMessage("email is required")

如果您的字段是必需的,您還可以添加.exists()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM