gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

Nested object properties reported as invalid even though parent object is optional. #191

Closed rudasn closed 8 years ago

rudasn commented 9 years ago

Note: I'm using tcomb-json-schema to convert a JSON schema to a tcomb object.

Consider an example JSON object describing a person.

{
  "type": "object",
  "properties": {
    "name": {
      "type": "object",
      "required": [ "first", "last" ],
      "properties": {
        "first": {
          "type": "string"
        },
        "middle": {
          "type": "string"
        },
        "last": {
          "type": "string"
        }
      }
    }
  }
}

The name property is optional, but it's first and last properties are required.

Observed behaviour If first, middle, last are all null, name is reported as

{
  "first": null,
  "middle": null,
  "last": null
}

and it's first and last properties do not pass the validation test (because they are required and null).

Expected behaviour If first, middle, last are all null, name should pass the validation test (because it's optional).

It is possible to support this kind of behaviour? Where should I start looking into implementing this?

gcanti commented 9 years ago

It is possible to support this kind of behaviour?

Optional structs are not supported. The simplest workaround I can think of is using a subtype:

function isValidName(x) {
  return (!t.Nil.is(x.first) && !t.Nil.is(x.last)) || (t.Nil.is(x.first) && t.Nil.is(x.last) && t.Nil.is(x.middle));
}

const Name = t.subtype(t.struct({
  first: t.maybe(t.String),
  middle: t.maybe(t.String),
  last: t.maybe(t.String)
}), isValidName);

const Foo = t.struct({
  name: Name
}, 'Person');

var options = {
  fields: {
    name: {
      error: 'my error message here'
    }
  }
};
rudasn commented 9 years ago

Thanks, that looks quite simple.

Does tcomb-json-schema support subtypes and custom validators?

gcanti commented 9 years ago

Does tcomb-json-schema support subtypes and custom validators?

No, AFAIK there's not standard for that, but I can be wrong.

VinSpee commented 8 years ago

@gcanti can you explain a little bit why optional Structs aren't supported?

gcanti commented 8 years ago

@VinSpee because of a simple reason: till now I didn't come up with a good idea on how to handle them. Let's talk about this topic, I'm quite interested https://github.com/gcanti/tcomb-form/issues/236