如何使用羊驼创建一个必需的条件字段?

时间:2017-09-08 20:23:33

标签: javascript forms alpacajs

有谁知道如何定义依赖于另一个字段的必填字段?

例如,如果field1标记为true,则必须field2,否则不应填写字段2.

这是我目前的尝试:

"field1": {
    "title": "Field1:",
    "type": "string",
    "enum": ["true", "false"]
},
"field2": {
    "title": "Field2:",
    "type": "integer",
    "dependencies": "field1",
    "required": true
}

1 个答案:

答案 0 :(得分:3)

如果不满足依赖项,羊驼的依赖项系统将隐藏依赖项字段,否则将显示该字段,并且还需要分配给它的任何选项(例如验证选项)。

浏览文档后,我注意到您必须在模式和选项对象中都设置依赖项。

JSON

{
  "view": "bootstrap-edit",
  "schema": {
    "type": "object",
    "properties": {
      "description_required": {
        "enum": [
          "Y",
          "N"
        ],
        "required": true
      },
      "description": {
        "required": true
      }
    },
    "dependencies": {
      "description": ["description_required"] // Specify the field that your conditional field is dependant on
    }
  },
  "options": {
    "fields": {
      "description_required": {
        "type": "select",
        "noneLabel": "Select an Option",
        "label": "Description Required"
      },
      "description": {
        "type": "textarea",
        "cols": 5,
        "label": "Description",
        "dependencies": {
          "description_required": "Y" // Specify the required value for the dependant field to show
        }
      }
    }
  }
}

在上面的示例中,我们简单地选择了 Y N 选项。如果选择了 Y ,那么我们会显示必填的文本区域,否则不会显示该文本区域。

实时示例

JSFiddle-记录表单对象中的注释。