首页 > 解决方案 > 使用填充字符串的自定义类型扩展 Joi

问题描述

我想为populatedStrings 创建一个自定义 Joi 类型,方法是使用.extend(..)以下类型创建一个类型joi.string()

到目前为止,我的尝试很接近:

    const StandardJoi = require("joi");

    const Joi = StandardJoi.extend(joi => ({
      base: joi.string(),
      name: "populatedString",
      language: {
        required: "needs to be a a string containing non whitespace characters"
      },
      pre(value, state, options) {
        value = value.trim();
        return value === "" ? undefined : value;
      },
      rules: [
        {
          name: "required",
          validate(params, value, state, options) {
            if (value === undefined) {
              return this.createError(
                "populatedString.required",
                { v: value },
                state,
                options
              );
            }

            return value;
          }
        }
      ]
    }));

它工作的例子

    Joi.populatedString().validate(" x "); // $.value === 'x'
    Joi.populatedString().validate("  "); // $.value === undefined

    // $.error.details
    //
    // [ { message: '"value" needs to be a a string containing non whitespace characters',​​​​​
    // ​​​​​    path: [],​​​​​
    // ​​​​​    type: 'populatedString.required',​​​​​
    // ​​​​​    context: { v: undefined, key: undefined, label: 'value' } } ]​​​​​
    Joi.populatedString()
      .required()
      .validate("  ");

    // $.value
    //
    // { inObj1: 'o' }
    Joi.object()
      .keys({
        inObj1: Joi.populatedString()
      })
      .validate({ inObj1: " o " });

但它不会失败(因为它应该)

    // ​​​​​{ error: null, value: {}, then: [λ: then], catch: [λ: catch] }​​​​​
    Joi.object()
      .keys({
        inObj2: Joi.populatedString(),
        inObj3: Joi.populatedString().required()
      })
      .validate({ inObj2: "  " });

即使inObj3is.required()和 not 提供它也不会失败。

标签: javascripthapijsjoi

解决方案


我设法解决了它:

    const BaseJoi = require("joi");

    const Joi = BaseJoi.extend(joi => ({
      base: joi.string(),
      name: "populatedString",
      language: {
        required: "needs to be a a string containing non whitespace characters"
      },
      pre(value, state, options) {
        value = value.trim();
        return value === "" ? undefined : value;
      },
      rules: [
        {
          name: "required",
          setup(params) {
            return this.options({ presence: "required" });
          },
          validate(params, value, state, options) {
            if (value === undefined) {
              return this.createError(
                "populatedString.required",
                { v: value },
                state,
                options
              );
            }

            return value;
          }
        }
      ]
    }));

修复方法是添加setup并让它presence = requiredrequired()被调用时设置选项。


推荐阅读