簡體   English   中英

使用 Joi 驗證時剝離未知密鑰

[英]Stripping unknown keys when validating with Joi

我正在使用 Joi 來驗證服務器中的 JavaScript 對象。 架構如下所示:

var schema = Joi.object().keys({
    displayName: Joi.string().required(),
    email: Joi.string().email(),
    enabled: Joi.boolean().default(false, "Default as disabled")
}).unknown(false);

如果對象中存在未知鍵,則上面的架構將報告錯誤,這是預期的,但我想要的是靜默剝離所有未知,而不會出錯。 有沒有可能做到?

如果要從正在驗證的對象中stripUnknown未知鍵,則需要使用stripUnknown選項。

https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback 上的cf 選項

const joi = require('joi');

joi.validate(object, schema, {stripUnknown:true}, callback);

與版本 14.3.4 一樣,此問題有一個簡單的解決方案。 這是為您解決問題的代碼。

// Sample data for testing.
const user = {
    fullname: "jayant malik",
    email: "demo@mail.com",
    password: "password111",
    username: "hello",
    name: "Hello"
};

// You define your schema here
const user_schema = joi
  .object({
    fullname: joi.string().min(4).max(30).trim(),
    email: joi.string().email().required().min(10).max(50).trim(),
    password: joi.string().min(6).max(20),
    username: joi.string().min(5).max(20).alphanum().trim()
  })
  .options({ stripUnknown: true });

// You validate the object here.
const result = user_schema.validate(user);

// Here is your final result with unknown keys trimmed from object.
console.log("Object with trimmed keys: ", result.value);

這是包含條帶未知選項的當前方法:

const validated = customSchema.validate(objForValidation, { stripUnknown: true });

如果您傳入的objForValidation具有未在customSchema定義的customSchema ,它將在驗證之前刪除該條目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM