Angular Schema Form - Require Field if Integer Field is Not Null

389 Views Asked by At

I am trying to create a form using the Angular JSON Schema Form. I want one field (dropdown1) to be required when another field (number1) is populated. I am able to get the following form + schema working in the SchemaForm.io Sandbox, but when I put it into my site, the dropdown field is missing.

Here is my schema:

{
"type": "object",
"properties": {
    "isChecked": {
        "title": "checked?",
        "type": "boolean"
    },
    "text1": {
        "title": "text1",
        "type": "number",
        "minimum": 0,
        "maximum": 100,
        "condition": "model.isChecked"
    },
    "number1": {
        "title": "number1",
        "type": "number",
        "minimum": 0,
        "condition": "model.isChecked"
    },
    "dropdown1": {
        "title": "",
        "type": "string",
        "enum": ["Days", "Months", "Years"],
        "condition": "model.isChecked"
    },
    "comment": {"type": "string", "Title": "Comment"}
}

}

Here is my form:

[
"isChecked",
{
    "key": "text1",
    "type": "decimal",
    "validationMessages": {
        "maximum": "text1 must be 100 or lower.",
        "minimum": "text1 must be 0 or higher.",
        "required": "This field is required"
    },
    "required": false
},
{
    "key": "number1",
    "type": "number",
    "validationMessages": {
        "minimum": "number1 must be 0 or higher."
    },
    "required": false
},
{
    "key": "dropdown1",
    "required": false,
    "condition": "model.number1 === null"
},
{
    "key": "dropdown1",
    "required": true,
    "condition": "model.number1 > 0",
    "validationMessages": {
        "required": "dropdown1 is required."
    }
},
{
    "key": "comment",
    "type": "textarea"
}

]

2

There are 2 best solutions below

0
On BEST ANSWER

Here is the solution I found:

"condition": {
                "functionBody": "return model.number1 === undefined && model.isChecked"
            }
0
On

You can use the "dependencies" property (https://json-schema.org/understanding-json-schema/reference/object.html#property-dependencies). The example requires billing_address to be present when a credit_card is provided:

{
  "type": "object",
  "properties": {
    "credit_card": {
      "type": "number"
    },
    "billing_address": {
      "type": "string"
    }
  },
  "dependencies": {
    "credit_card": [
      "billing_address"
    ]
  }
}

This implementation supports "dependencies": https://github.com/dashjoin/json-schema-form

You can check out the online example here: https://dashjoin.github.io/#/example/dependencies