表达Yup显示所有字段的所有错误

问题描述 投票:0回答:1

我是表达新手,但不是编程新手。我创建了一个验证中间件,它使用 yup 来验证发送到服务器的正文

用户路由.ts

import validate from "@middlewares/validationMiddleware.ts";
import userSchema from "@schemas/models/userSchema.ts";

router.post("/signup", validate(userSchema), signupUser); #signupUser is the controller/service for logic

用户架构.ts

import * as Yup from "yup";

const userSchema = Yup.object({
  body: Yup.object().shape({
    password: Yup.string()
      .min(8, "Password must be at least 8 characters")
      .matches()... // there are 4 matches here. too much code if I add all
      .required(),
    confirmPassword: Yup.string()
      .min(8, "Password must be at least 8 characters")
      .matches()... // there are 4 matches here. too much code if I add all
      .oneOf([Yup.ref("password"), undefined], "Passwords must match")
      .required(),
  }),
});

export default userSchema;

验证中间件.ts

import { NextFunction, Request, Response } from "express";
import { AnySchema, ValidationError } from "yup";

const validate =
  (schema: AnySchema) =>
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      await schema.validate(
        {
          body: req.body,
          query: req.query,
          param: req.params,
        },
        {
          abortEarly: false, // get all errors on all fields
        }
      );

      next();
    } catch (e) {
      if (e instanceof ValidationError) {
        console.log(e.errors); // shows all errors as an array (no key)
        const validationErrors: any = {};
        e.inner.forEach((error) => {
          if (error.path) {
            validationErrors[error.path] = error.message;
          }
        });
        console.log(validationErrors); // displays errors as an object but value is only 1 of the errors
        return res.status(400).json(validationErrors);
      }
      return res.status(500).send("Internal Server Error");
    }
  };

export default validate;

输出

  // e.errors
  [
   'Password must have 1 lowercase character',
   'Password must have 1 digit character',
   'Password must have 1 uppercase character',
   'Password must be at least 8 characters',
   'body.password is a required field',
   'Password must have 1 lowercase character',
   'Password must have 1 digit character',
   'Password must have 1 uppercase character',
   'Password must be at least 8 characters',
   'body.confirmPassword is a required field'
 ]

 // validationErrors
 {
   'body.password': 'body.password is a required field',
   'body.confirmPassword': 'body.confirmPassword is a required field'
 }

正如您在我的代码和输出中看到的,

e.errors
具有我想要返回的所有验证错误,但它是以数组形式返回的,所以我不知道应该在
validationErrors
中添加它们的字段作为对象返回,但每个字段只有 1 个错误。

我该如何进行?

typescript express validation mern yup
1个回答
0
投票

我想我找到了答案。

if (error.path) {
   validationErrors[error.path] = error.message;
}

error.path
有多个
error.message
所以应该是这样

if (error.path) {
  if (!validationErrors[error.path]) {
    validationErrors[error.path] = []; // Initialize array message
  }
  validationErrors[error.path].push(error.message); // push message to array
}
© www.soinside.com 2019 - 2024. All rights reserved.