簡體   English   中英

當 object 架構無效時,如何強制 joi 調用自定義 function?

[英]How to force joi to invoke custom function when the object schema is invalid?

我在我的Joi模式中創建了一個自定義 function 來驗證 name 是否equal confirmName

我使用abortEarly: false來獲取所有錯誤。

問題是當object中的驗證失敗時, custom function 不會調用。

目前結果birthYear僅適用於出生年份。 它應該是birthYearcustom

有沒有辦法讓它像我描述的那樣工作?

{ name: "foo", confirmName: "oo", birthYear: 0 },

代碼框.io

const Joi = require("joi");

console.clear();

const schema = Joi.object({
  name: Joi.string(),
  confirmName: Joi.string(),
  birthYear: Joi.number().integer().min(1900).max(2013)
}).custom((doc, helpers) => {
  const { name, confirmName } = doc;
  if (name !== confirmName) {
    throw new Error("name not match!!");
  }
});

const { error } = schema.validate(
  { name: "foo", confirmName: "oo", birthYear: 0 },
  { allowUnknown: true, abortEarly: false }
);

console.log({ error });

if (error) {
  const { details } = error;
  console.log({ details });
}

您不需要自定義驗證來確保name等於confirmName

只需使用對值的引用

const schema = Joi.object({
  name: Joi.string(),
  confirmName: Joi.ref('name'),
  birthYear: Joi.number().integer().min(1900).max(2013)
});

如果你想覆蓋錯誤信息,你可以使用.messages

confirmName: Joi.string().required()
                         .valid(Joi.ref('name'))
                         .messages({'any.only': 'name not match!!'})

暫無
暫無

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

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