Nodejs後端:驗證表單資料
阿新 • • 發佈:2022-02-23
Nodejs後端:驗證表單資料
使用 joi
第三方包,
1. 安裝 joi 包
npm install [email protected]
2. 使用示例
// 匯入joi模組
const joi = require('joi')
// 定義驗證規則
const schema = {
// username必須是字串型別、最小長度是2、最大長度是6、必填項、自定義驗證失敗錯誤資訊
username: joi.string().min(2).max(6).required().error(new Error('使用者名稱格式不正確')),
// email必須是字串型別、必須符合郵箱格式、必填項、自定義驗證失敗錯誤資訊
email: joi.string().email().required().error(new Error('郵箱格式不正確')),
// pwd必須是字串型別、必須符合指定的正則規則、自定義驗證失敗錯誤資訊
pwd: joi.string().regex(/^[a-zA-Z0-9]+$/).error(new Error('密碼格式不正確')),
// sex必須是數字型別、值是0或1、必填項、自定義驗證失敗錯誤資訊
sex:joi.number().valid(0,1).required().error(new Error('性別格式不正確'))
}
// 要驗證的物件
const user = {
username: 'admin',
email: '[email protected]',
pwd: 'abc123',
sex:0
}
// validate方法驗證user是否符合規則
joi.validate(user, schema).then((val) => {
console.log(val)
console.log('驗證通過')
}).catch((err) => {
console.log(err)
})