Reputation: 31595
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
?
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
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