如何使用 JSON 指针访问 minLength 属性?

问题描述 投票:0回答:1

鉴于下面的

schema
,我如何访问
minLength
属性来动态向用户显示需要多少个字符?

export const schema = {
  type: 'object',
  properties: {
    inputControl: {
      type: 'string',
      format: 'email',
      minLength: 10,
      errorMessage: {
        minLength: 'String must contain at least ${1/minLength} character(s)',
        format: 'Please enter valid email',
      }
    },
  },
}

我尝试过

${1/minLength}
和许多其他选项,但一切都返回
undefined
或引发错误。我得到的最好的是
${0#}
,它返回
inputControl

jsonschema jsonpointer
1个回答
0
投票

要使用 JSON 指针访问架构中的

minLength
属性,您可以使用特定的 JSON 指针字符串导航到该属性。在您的情况下,
minLength
属性位于
inputControl
对象内部,该对象位于
properties
内。

要访问此属性,您可以使用以下指针字符串:

/properties/inputControl/minLength

您可以将此字符串与支持 JSON 指针的库一起使用来提取值。例如,在 JavaScript 中,您可以使用

jsonpointer
json-ptr
等库来访问值。

这是使用

jsonpointer
库的示例:

const jsonpointer = require('jsonpointer');

const schema = {
  type: 'object',
  properties: {
    inputControl: {
      type: 'string',
      format: 'email',
      minLength: 10,
      errorMessage: {
        minLength: 'String must contain at least ${1/minLength} character(s)',
        format: 'Please enter valid email',
      }
    },
  },
};

const minLengthPath = '/properties/inputControl/minLength';
const minLength = jsonpointer.get(schema, minLengthPath);

console.log(minLength); // Output: 10

在此示例中,

jsonpointer.get
使用指针字符串导航到架构并返回所需的值。

关于在文本中使用

minLength
的问题,不能直接使用表达式
${1/minLength}
。相反,您需要手动将
${1/minLength}
替换为适当的值。您可以使用格式化字符串的函数来完成此操作。这是一个例子:

const errorMessageTemplate = schema.properties.inputControl.errorMessage.minLength;
const minLengthValue = jsonpointer.get(schema, minLengthPath);
const errorMessage = errorMessageTemplate.replace('${1/minLength}', minLengthValue);

console.log(errorMessage); // Output: "String must contain at least 10 character(s)"

此处,

${1/minLength}
替换为从架构中检索到的实际
minLength
值。

© www.soinside.com 2019 - 2024. All rights reserved.