BearStudio/formiz

Allow the message object in validations prop to be a function

DecampsRenan opened this issue · 2 comments

Is your feature request related to a problem? Please describe.
I need to get the error from a useField wrapped component (CardElement from react stripe). This component has only the onChange event, regarding there was an error or not. The only way to get the error is to get the value returned from this component

Describe the solution you'd like
I would like the message string in validations array to be a function that return a string, or a string. So i can use it like this:

<StripeCardInput
  label="Card Informations"
  name="cardInfos"
  validations={[
    {
      rule: isRequired(),
      message: 'You need to fill your card infos',
    },
    {
      rule(value) {
        return !(value && value.error);
      },
      message: (value) => value.error,
    },
  ]}
/>

Describe alternatives you've considered
Know i'm trying to use the form.invalidateFields inside a useEffect

const form = useForm();
const { values, invalidateFields } = form;
const { cardInfos } = values;

useEffect(() => {
  if (cardInfos && cardInfos.error) {
    invalidateFields({ cardInfos: cardInfos.error.message });
  }
}, [cardInfos, form, invalidateFields]);

The following code should works without passing a function.

<StripeCardInput
  label="Card Informations"
  name="cardInfos"
  validations={[
    {
      rule: isRequired(),
      message: 'You need to fill your card infos',
    },
    {
      rule(value) {
        return !(value && value.error);
      },
      message: form.cardInfos && form.cardInfos.error,
    },
  ]}
/>

Tell me if it helps :)

Thanks !