JSON Schema draft-07:按属性值设必填属性失败求助
解决JSON Schema中条件必填的问题
你的核心问题是if条件里的属性名写错了,导致规则没有触发。以下是修正后的完整Schema,同时保留你原来的显示控制逻辑:
"authorizationNumber": { "type": "object", "format": "grid-strict", "required": ["firstProperty"], "if": { "properties": { "firstProperty": { "const": true } }, "required": ["firstProperty"] // 确保属性存在,原schema已必填,此处让逻辑更严谨 }, "then": { "required": ["secondProperty"] }, "properties": { "firstProperty": { "type": "boolean", "default": false, "options": { "grid_columns": 3 } }, "secondProperty": { "type": "array", "format": "select2", "uniqueItems": true, "minItems": 1, "items": { "type": "string", "$ref": "#/definitions/serviceCode" }, "options": { "dependencies": { "firstProperty": true }, "select2": { "closeOnSelect": true, "tags": false }, "grid_columns": 4 } } } }
关键修正说明:
- 修正if条件的属性名:把错误的
authorizationNumberAvailable改成实际要判断的firstProperty,确保条件能正确触发 - 保留显示控制逻辑:原有的
options/dependencies继续生效,保证firstProperty为true时secondProperty才会显示 - 生效条件必填规则:then块里的
required: ["secondProperty"]会在firstProperty为true时,强制要求该属性必须存在
这样修改后,就能实现你要的需求:当firstProperty设为true时,secondProperty既会显示,也会被设为必填项。
内容的提问来源于stack exchange,提问作者shukhrat
相关产品推荐
相关产品推荐

