Vencovsky
Vencovsky

Reputation: 31595

Formik Field validate using Yup

I was looking at the docs, and you can validate a Field by passing validate to Field which is a function.

e.g.

const validate = value => {
  let errorMessage;
  if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
    errorMessage = 'Invalid email address';
  }
  return errorMessage;
};

...

<Field validate={validate} name="email" type="email" />

How can I substitute the function validate to use Yup ?

If you are going to ask why I'm doing this...

Instead of having a huge validationSchema object, I want to pass a Yup validation object directly to Field because my form is dynamic generated.

Upvotes: 0

Views: 488

Answers (1)

Ciar&#225;n Tobin
Ciar&#225;n Tobin

Reputation: 7526

It seems like Formik doesn't provide a way to do this natively for some reason. You could do it like this:

<Field
  name="email"
  type="email"
  validate={value =>
    Yup.string()
      .matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i, "Invalid")
      .validate(value)
      .then(() => undefined)
      .catch(({ errors }) => errors[0])
  }
/>

Working example on CodeSandbox.

Upvotes: 1

Related Questions