express使用joi進(jìn)行數(shù)據(jù)校驗(yàn)

官網(wǎng):https://joi.dev/api/?v=17.3.0#introduction

新建一個文件夾validate,在該文件夾下創(chuàng)建一個index.js,
做了一個的中間件
代碼如下:

image.png

具體代碼

const Joi = require("joi")
module.exports = {
    roles(data = {}, errMsg = {}, content = "body") {
        data.token = Joi.allow();//忽略token的校驗(yàn)
        const schema = Joi.object(data)
        return async function (req, res, next) {
            try {
                const value = await schema.validateAsync(req[content], data);
                console.log(value);
                next();
            } catch (error) {
                res.json({
                    code: 400,
                    message: error.message ? error.message : errMsg[error.details[0].context.key]
                })
            }
        }
    }
}

在路由中配置如下:
1). rule 定義校驗(yàn)規(guī)則
2). message 自己定義提示


image.png

//1.引入express模塊
const express = require("express");
//3.引入控制層
const { login, register } = require("../controller/userContoller");
const Joi = require("joi")
//2.創(chuàng)建路由對象
const userRouter = express.Router();

//4.配置對應(yīng)控制器的方法
userRouter.post("/login", require("../validate").roles({
    name: Joi.string().min(5).max(12).required().error(new Error("用戶名不合法")),//自己定義提示內(nèi)容
    password: Joi.string().required(),
    // token:Joi.string()
}, {
    password: "密碼不合法", //也可以在這里 定義提示內(nèi)容
    name: "用戶名不合法"
}), login);

userRouter.post("/reg", register);
module.exports = {
    userRouter
}

JavaScript對象的規(guī)則描述語言和驗(yàn)證器。

引入Joi模塊

    cnpm i joi -D

規(guī)則

 Joi.string()/Joi.number():定義只能是字符串/數(shù)字類型
 Joi.alphanum():只能是字母字符串或者數(shù)字字符串
 Joi.min()/max():限制字符串最大最小長度
 Joi.required():此屬性必填
 Joi.error():自定義錯誤信息
 Joi.regex():接收一個字符串規(guī)則驗(yàn)證
 [Joi.string(), Joi.number()]:可以時字符串也可以是數(shù)字類型
 Joi.integer():必須是整數(shù)

定義一個規(guī)則

const schema = {
    username: Joi.string().alphanum().min(3).max(30).required().error(new       
    Error(‘自定義錯誤信息’)),
    password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),
    access_token: [Joi.string(), Joi.number()],
    birthyear: Joi.number().integer().min(1900).max(2013),
    email: Joi.string().email()
};

校驗(yàn)

   Joi.validate({ username: 'abc', birthyear: 1994 }, schema);
  //或者
  schema.validateAsync({ username: 'abc', birthyear: 1994 },規(guī)則)

{ allowUnknown: true } //忽略 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容