gcanti / tcomb-form

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

Custom Validation for the whole form #339

Closed anpr closed 8 years ago

anpr commented 8 years ago

Thanks for the excellent library!

Version

I would like to have a custom validation for my form that allows me to specify that at least one of two attributes must be specified. How can I do this? All I've found is that I can specify custom validation through subtypes, but this doesn't work in this (right?).

Example:

const type = t.struct({
    supplier_article_number: t.maybe(t.String),
    gtin: t.maybe(t.String)
)};

// I want to validate that *either* supplier_article_number *or* gtin must be specified.
gcanti commented 8 years ago

All I've found is that I can specify custom validation through subtypes

Yep:

const atLeastOne = ({ supplier_article_number, gtin }) => !t.Nil.is(supplier_article_number) || !t.Nil.is(gtin)

const Type = t.refinement(t.struct({
  supplier_article_number: t.maybe(t.String),
  gtin: t.maybe(t.String)
}), atLeastOne)

const options = {
  error: 'At least one!'
}
anpr commented 8 years ago

Stupid me, thanks for the example!