安装
npm install express-joi
依赖
npm install joi@17.4.0
导入
const expressJoi = require('@escook/express-joi')
使用
const express = require('express')
const app = express()
const Joi = require('joi')
const expressJoi = require('@escook/express-joi')
app.use(express.urlencoded({ extended: false }))
const userSchema = {
body: {
username: Joi.string().alphanum().min(3).max(12).required(),
password: Joi.string()
.pattern(/^[\S]{6,15}$/)
.required(),
repassword: Joi.ref('password')
},
query: {
name: Joi.string().alphanum().min(3).required(),
age: Joi.number().integer().min(1).max(100).required()
},
params: {
id: Joi.number().integer().min(0).required()
}
}
app.post('/adduser/:id', expressJoi(userSchema), function (req, res) {
const body = req.body
res.send(body)
})
app.use(function (err, req, res, next) {
if (err instanceof Joi.ValidationError) {
return res.send({
status: 1,
message: err.message
})
}
res.send({
status: 1,
message: err.message
})
})
app.listen(3001, function () {
console.log('Express server running at http://127.0.0.1:3001')
})
验证规则
更多的验证规则,请参考 Joi 的官方文档。
开源协议