nodejs 定义错误验证机制

//专门验证机制
/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)
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你的美,让我痴迷

你的好,我会永远记住你的。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值