我是新手,不会表达,但不会编程.我已经创建了一个验证中间件,它使用YUP来验证发送到服务器的正文
UserRoutes.ts
import validate from "@middlewares/ValidationMiddleware.ts";
import userSchema from "@schemas/models/用户架构.";
router.post("/signup", validate(userSchema), signupUser); #signupUser is the controller/service for logic
用户架构.
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;
ValidationMiddleware.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
中,它是作为对象返回的,但每个字段只有一个错误.
我应该如何继续呢?