簡體   English   中英

在 Joi 驗證中忽略“必需”?

[英]Ignoring "required" in Joi validation?

我正在嘗試使用 Joi 來驗證 RESTful Web 服務接受的數據模型。

對於創建操作,我想對字段強制執行“必需”驗證。 但是,對於更新操作,可能會提交部分數據對象,因此我希望忽略“必需”屬性。

除了創建兩個模式之外,有沒有辦法實現這一點?

您可以通過使用optionalKeys擴展第一個模式來避免這兩個模式。

const createSchema = Joi.object().keys({
  name: Joi.string().required(),
  birthday: Joi.date().required(),
});

const updateSchema = createSchema.optionalKeys("name", "birthday");

Joi.validate({name: "doesn't work"}, createSchema); // error: birthday field missing
Joi.validate({name: "it works"}, updateSchema); // all good

使用.fork()您可以傳入您想要的字段數組。

const validate = (credentials, requiredFields = []) => {

  // Schema
  let userSchema = Joi.object({
    username: Joi.string(),
    email: Joi.string().email(),
  })

  // This is where the required fields are set
  userSchema = userSchema.fork(requiredFields, field => field.required())

  return userSchema.validate(credentials)
}

validate(credentials, ['email'])

或者做相反的事情並將它們更改為可選。

使用alter方法可以實現您想要的結果。 這是一個例子。

const validateUser = (user, requestType) => {
  let schema = Joi.object({
    email: Joi.string().email().required(),
//Here, we want to require password when request is POST. 
//Also we want to remove password field when request is PUT
    password: Joi.string()
      .min(1)
      .max(256)
      .alter({
//For POST request
        post: (schema) => schema.required(),
//For PUT request
        put: (schema) => schema.forbidden(),
      }),
  });

  return schema.tailor(requestType).validate(user);
};

然后在我們的路由中,我們調用函數並傳遞參數,如下所示:

//For POST
const { error } = validateUser({email: "me@mail.com"}, "post");//error: "password is a required field" 
//For PUT 
const { error } = validateUser({email: "me@mail.com"}, "put");//error: undefined (no error)

使用.when()並根據條件設置.required()

您可以通過將 Joi.string()... 替換為您作為用戶名傳遞的確切值來跳過 Joi 驗證。 在示例中,我已將空用戶名傳遞給 api。

同樣在條件基礎上,您可以跳過 joi 驗證

let userSchema = Joi.object({
   username: "",
   email: <some condition> === true ? "" : Joi.string().required()
})

暫無
暫無

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

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