簡體   English   中英

如何在joi模式中運行自定義驗證功能

[英]How to run custom validation function in the joi schema

我要基於架構中未包含的內容將字段設置為強制或可選。 例如,某些東西存儲在全局范圍內。 這是Joi模式:

first_name: Joi.string().min(2).max(10).regex(Regex.alphabeta, 'alphabeta').error(JoiCustomErrors)

如果some_global_scope_var為1,如何使first_name為必填some_global_scope_var ,否則將其some_global_scope_var可選?

注意: some_global_scope_var不是架構的一部分。

使用$字符訪問全局范圍

通常,您將訪問沒有前綴的相對屬性last_name 對於全局訪問,請在變量前加上$

完整的解決方案

const Joi = require('@hapi/joi');

global.app = {
  someValue: 1,
};

const schema = Joi.object().keys({
  first_name: Joi.string()
                 .min(2)
                 .max(10)
                 .when('$app.someValue', {
                   is: Joi.equal(1),
                   then: Joi.required(),
                 })
});

const value = {
  first_name: 'a1300',
};

const result = schema.validate(value);
console.log(JSON.stringify(result.error, null, 2));

PS我省略了regex(Regex.alphabeta, 'alphabeta').error(JoiCustomErrors)

暫無
暫無

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

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