shakacode / re-formality

Form validation tool for reason-react
https://re-formality.now.sh
MIT License
244 stars 36 forks source link

Optional `metadata` type #82

Closed alex35mil closed 3 years ago

alex35mil commented 4 years ago

Sometimes, converting input to output requires some additional metadata. E.g. there is a select in UI with a list of items, each item is of Foo.t type which is a record {id: int, label: string}. Select's value is stringified id. In the output, there should be Foo.t. To get the output value in validator, array(Foo.t) is required.

It's achievable in the current state of things by:

But neither looks nice to me.

Proposal: introduce an optional metadata type. If defined, it would be passed as a second argument to validators.

module Foo = {
  type t = {
    id: int,
    label: string,
  };
};

module Form = [%form
  type input = {foo: string};
  type output = {foo: Foo.t};
  type metadata = {foos: array(Foo.t)};
  let validators = {
    foo: {
      strategy: OnFirstChange,
      validate: (input, metadata) =>
        switch (
          metadata.foos
          ->Array.getBy(foo =>
              input.foo
              ->Int.fromString
              ->Option.mapWithDefault(false, id => id == foo.id)
            )
        ) {
        | Some(foo) => Ok(foo)
        | None => Error("Invalid foo")
        },
    },
  }
];

[@react.component]
let make = (~foos: array(Foo.t)) => {
  let form = Form.useForm(
    ~initialInput={foo: ""},
    ~metadata={foos: foos},
    ~onSubmit={...}
  );
  ...
};
johnhaley81 commented 4 years ago

We have this use case quite often and so far we have been putting it into another field on the input which is definitely clumsy and doesn't feel correct. Adding a data or metadata sounds like a fantastic change to me.

alex35mil commented 4 years ago

metadata sounds perfect 👍

danwetherald commented 3 years ago

We would love to have this concept to separate "hacky" fake inputs to a designated location to store data later needed to run validations.

One thing to mention here. We would require an API that allows us to update these metadata fields as these can be dynamic or change at a later time.

danwetherald commented 3 years ago

I would love to help make this happen but the PPX stuff is a bit over my head, is there anything we can do to speed this feature up?

alex35mil commented 3 years ago

@dan003400 I will look into this in upcoming weeks