//专门验证机制
/schema/user.js 用户验证机制
//导入定义规则的包
const joi=require('joi')
//定义用户名或密码的验证规则
const username=joi.string().alphanum().min(1).max(10).required().error(new Error('用户名最少1位,最多10位,只能是字母或者数字'))
const password=joi.string().pattern(/^[\S]{6,12}$/).required().error(new Error('密码最少6位,最多12位'))
//参考
// username:Joi.string().min(2).max(12).required().error(new Error('用户名不符合验证规则')),
// email:Joi.string().email().required().error(new Error('邮箱格式不符合要求')),
// password:Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error('密码格式不符合要求')),
// role:Joi.string().valid('normal','admin').required().error(new Error("角色值非法")),
// state:Joi.number().valid(0,1).required().error(new Error('状态值非法'))
//定义注册或登录表单数据的规则对象
exports.reg_login_schema={
body:{
username,
password
},
}
使用:
//2.导入需要的验证规则对象
const {reg_login_schema}=require('../schema/user')
//注册新用户
router.post('/reguser',expressJoi(reg_login_schema), user_handler.regUser)
//登录
router.post('/login',expressJoi(reg_login_schema),user_handler.login)
全局定义:
//导入定义规则的包
const joi=require('@hapi/joi')
//定义错误级别文件
app.use((err,req,res,next)=>{
//验证失败导致的错误
if(err instanceof joi.ValidationError) return res.cc(err)
//未知错误
res.cc(err)
})