node.js 使用joi來驗證數據模型


        joi是nodej的一個工具模塊,主要用於JavaScript對象的校驗。它是一種簡單易用的javacript對象約束描述語言,可以輕松解決nodejs開發中的各種參數的校驗。

 

  直接上代碼

// 導入joi模塊 
const joi = require('joi')

// 定義驗證規則
const schema = joi.object({
    // 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('性別格式不正確')),
   // 可以根據sex的值來定義name2的類型屬性 name2: joi.when('sex', { is: 1, then: joi.string().required().error(new Error('name2格式不正確')) }),
name3: joi.string().max(
2).allow('').error(new Error('name3格式不正確')),
   // 針對數組的操作 orderItems: joi.array().items( joi.object().keys({ thirdOrderItemId: joi.string().required().error(
new Error('訂單明細ID不能為空')), productName: joi.string().required().error(new Error('商品名稱不能為空')) }) ) }); let body = { username: "adm", email: 'admin@qq.com', pwd: 'abc123', sex: 1, phone: '13', name2: "1", name3: "", orderItems: '[{\"thirdOrderItemId\": \"123\",\"productName\": \"151515\"}]' }; body.orderItems = JSON.parse(body.orderItems) // 針對數組操作必須是json對象,如果是json字符串需要自己解析一次。 async function run() { try { /*驗證*/ await schema.validateAsync(body, { allowUnknown: true, abortEarly: true }); console.log('驗證成功'); } catch (e) { console.log(e.message); } }
run();

  另外還有一些基本的操作粘在下面以作參考

// 3 - 30 個 數字、字符
username: Joi.string().alphanum().min(3).max(30).required(),

// 3 - 30 位 字母數字組合密碼
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/),

// string || number 都可以通過
access_token: [Joi.string(), Joi.number()],

// 生日限制
birthyear: Joi.number().integer().min(1900).max(2018),

// email 限制
email: Joi.string().email(),

// URI限制
website: Joi.string().uri({ scheme: [ 'git', /git+https?/ ] }),

// ==== 允許為空/ 否認不允許為空 ====
search: Joi.string().allow(''),

// 驗證枚舉值,如果不傳,默認為all
type: Joi.string().valid('disabled', 'normal', 'all').default('all'),

// 開始時間 會自動格式化
startTime: Joi.date().min('1-1-1974').max('now'),

// 結束時間 必須大於開始時間,小於2100-1-1
endTime: Joi.when(Joi.ref('startTime'), { is: Joi.date().required(), then: Joi.date().max('1-1-2100') }),

// 頁碼 限制最小值
page: Joi.number().integer().min(1).default(1), pageSize: Joi.number().integer().default(8),
// deleteWhenLtTen: Joi.number().integer().max(10).strip(),

// 數組中包含某個字段 && 數字
arrayString: Joi.array().items(
// 數組中必須包含 name1
Joi.string().label('name1').required(),
// 數組中必須包含 數字
Joi.number().required(),
// 除掉【以上類型的以外字段】---數組中可以包含其他類型,如bool
Joi.any().strip()
),

// 數組對象, 如需其參考以上字段
arrayObject: Joi.array().items(
Joi.object().keys({
age: Joi.number().integer().max(200),
sex: Joi.boolean()
})
)

with('isA', 'AVal') //意思是,isA 和 AVal 這兩字段如果填寫了isA,也必須要填寫AVal
with('isB', 'BVal') //道理同上
without('isA', 'isB'); //意思是 isA 和 isB 只能填寫其中一個
or('isA', 'isB') //意思是 isA 和 isB 這兩字段至少填寫其一

 

值得注意的地方是:在安裝的時候一定要指定版本,然后根據指定版本的文檔去看詳細的操作。

allowUnknown - 如果為 true,則允許對象包含被忽略的未知鍵。 默認為 false。

abortEarly - 當為真時,停止對第一個錯誤的驗證,否則返回找到的所有錯誤。 默認為  true。

例如:

    npm install joi@17.3.0

官方文檔https://joi.dev/api/?v=17.4.2

github地址https://github.com/sideway/joi/blob/v17.3.0/API.md


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM