我是表达新手,但不是编程新手。我创建了一个验证中间件,它使用 yup 来验证发送到服务器的正文
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
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;
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 个错误。
我该如何进行?
我想我找到了答案。
在
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
}