【发布时间】:2019-03-18 12:06:22
【问题描述】:
我正在设计一个使用 JSON Schema 建模的 Web 应用程序。我正在尝试创建一个带有文本区域和复选框的页面。文字区是解释我为什么喜欢披萨。如果用户点击复选框,他们确认他们不喜欢披萨。除非选中该复选框,否则该文本框是“必需的”。该复选框实际上作为布尔值运行,但无法更改正在使用的组件(因为用户研究人员是这样说的)。目前,我正在使用 AJV 来验证我的架构,它配置为在属性为 required 但未输入/选择任何输入时抛出 errorMessages.required。
不幸的是,我对 JSON 架构完全没有经验。以下是我目前试图验证这一点的尝试。这可以正确呈现,但不能按我的意愿工作 - 在我的开发环境中,它只会验证任何内容,但在 jsonschemavalidator.net 上,除非选中该复选框,否则它不会验证。如何实现我想要的功能?
{
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
additionalProperties: false,
propertyNames: {
enum: [
'q-why-i-love-pizza',
'q-i-hate-pizza'
]
},
properties: {
'q-why-i-love-pizza': {
type: 'string',
title: 'If you love pizza, tell us why',
maxLength: 500,
errorMessages: {
required: "Please tell us why you love pizza, or select 'I hate pizza'"
}
},
'q-i-hate-pizza': {
type: 'array',
maxItems: 1,
uniqueItems: true,
items: {
anyOf: [
{
title: 'I hate pizza',
const: 'hate'
}
]
},
errorMessages: {
required: "Please tell us why you love pizza, or select 'I hate pizza'"
}
}
},
allOf: [
{
$ref: '#/definitions/if-not-checked-then-q-why-i-love-pizza-is-required'
}
],
definitions: {
'if-not-checked-then-q-why-i-love-pizza-is-required': {
if: {
not: {
properties: {
'q-i-hate-pizza': {
const: 'hate'
}
}
}
},
then: {
required: ['q-why-i-love-pizza'],
propertyNames: {
enum: [
'q-i-hate-pizza',
'q-why-i-love-pizza'
]
}
}
}
}
}
编辑:
我希望得到以下结果:
{
'q-why-i-love-pizza' : '',
'q-i-hate-pizza' : ['']
}
这应该验证失败,因为没有选择任何值。
{
'q-why-i-love-pizza' : 'I love pizza because it's amazing',
'q-i-hate-pizza' : ['']
}
这应该通过,因为用户已经输入了他们喜欢披萨的原因,因此不需要单击复选框。
{
'q-why-i-love-pizza' : '',
'q-i-hate-pizza' : ['hate']
}
这应该通过,因为虽然用户没有告诉我们他们为什么喜欢披萨,但他们已经选中了该框以表明他们讨厌披萨。
{
'q-why-i-love-pizza' : 'I am a user, so decided to tell you I hate pizza too',
'q-i-hate-pizza' : ['hate']
}
这也应该通过,因为我需要接受这样的可能性,即用户会在方框中打勾表示他们讨厌披萨,但无论如何都要继续告诉我。
解决方案:
{
type: "object",
properties: {
'q-why-i-love-pizza': {
type: 'string',
title: 'If you love pizza, tell us why',
maxLength: 500,
errorMessages: {
required: "Please tell us why you love pizza, or select 'I hate pizza'"
}
},
'q-i-hate-pizza': {
type: 'array',
maxItems: 1,
uniqueItems: true,
items: {
anyOf: [
{
title: 'I hate pizza',
const: 'hate'
}
]
},
errorMessages: {
required: "Please tell us why you love pizza, or select 'I hate pizza'"
}
}
},
allOf: [
{ $ref: "#/definitions/if-not-checked-then-q-offender-contact-description-is-required" }
],
definitions: {
"if-not-checked-then-q-offender-contact-description-is-required": {
if: {
not: {
required: ["q-i-hate-pizza"]
}
},
then: {
required: ["q-why-i-love-pizza"]
}
}
}
}
【问题讨论】:
标签: jsonschema json-schema-validator ajv