【问题标题】:Why Node js joi validation is not working as expected?为什么 Node js joi 验证没有按预期工作?
【发布时间】:2021-09-16 13:06:06
【问题描述】:

我已经为我的项目实施了 joi 验证,但它不适用于任何单个字段。无论您传递什么,它都会存储在数据库中,即使我做了验证代码,它也不会验证任何字段 这是验证代码

import * as Joi from "joi";
import { Request, Response, NextFunction } from 'express';
import { StatusCodes } from 'http-status-codes';
import { sendError } from "../responseHelper";
import { validationOptions } from "./_index";

export class CountryValidator {

    public async createCountryValidator(req: Request, res: Response, next: NextFunction) {

        try {
            const schema = Joi.object({
                id: Joi.number().required(),
                name: Joi.string().required(),
                code: Joi.string().required(),
                status: Joi.number().valid(0, 1).required(),
            });
            schema.validate(req.body, validationOptions);
            next();
        } catch (error) {
            sendError(res, error, error.code, StatusCodes.INTERNAL_SERVER_ERROR);
        }
    }
}

这是我的路线路径

adminRoute.route('/country/create')
    .post(countryValidator.createCountryValidator, countryController.createCountry);

在这条路径上,我在下面发布的数据根据​​验证完全错误,但它仍然接受所有数据并且没有抛出任何验证错误

{
    "name":"BR1Z",
    "code":100,
    "status":"1"
}

谁能帮我解决这个问题?

【问题讨论】:

    标签: node.js express validation joi


    【解决方案1】:

    schema.validate 返回带有error 字段的对象(而不是抛出错误)。

    ...
        const joiRes = schema.validate(req.body, validationOptions);
        if(joiRes.error){
            sendError(res, error, error.code, StatusCodes.INTERNAL_SERVER_ERROR);
        }
    ...
    

    见:https://joi.dev/api/?v=17.4.1

    【讨论】:

    • 非常感谢@Daniel 的帮助和支持。这个解决方案对我有用
    猜你喜欢
    • 2022-10-15
    • 2018-08-16
    • 2020-04-10
    • 2017-12-26
    • 1970-01-01
    • 2014-08-04
    • 2021-01-03
    • 2018-11-08
    • 1970-01-01
    相关资源
    最近更新 更多