Forked from manzoorwanijk/yup-with-final-form.js
Last active
November 3, 2022 09:33
-
-
Save milantarami/dd13e1cf5b7e91e01c641514ff9806ef to your computer and use it in GitHub Desktop.
How to properly use yup validation schema with (React) Final Form?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as yup from 'yup'; | |
| import { setIn } from 'final-form'; | |
| const validationSchema = yup.object({ | |
| email: yup.string().email(), | |
| shipping: yup.object({ | |
| name: yup.string(), | |
| phone: yup.object({ | |
| code: yup.string().matches(/^\+\d+$/i), | |
| number: yup.number().max(10), | |
| }), | |
| address: yup.string(), | |
| zip: yup.string(), | |
| }), | |
| billing: yup.object({ | |
| name: yup.string(), | |
| address: yup.string(), | |
| zip: yup.string(), | |
| }), | |
| items: yup.array().of( | |
| yup.object({ | |
| id: yup.number(), | |
| price: yup.number(), | |
| quantity: yup.number(), | |
| }) | |
| ), | |
| }); | |
| // To be passed to React Final Form | |
| const validateFormValues = (schema) => async (values) => { | |
| if (typeof schema === 'function') { | |
| schema = schema(); | |
| } | |
| try { | |
| await schema.validate(values, { abortEarly: false }); | |
| } catch (err) { | |
| const errors = err.inner.reduce((formError, innerError) => { | |
| return setIn(formError, innerError.path, innerError.message); | |
| }, {}); | |
| return errors; | |
| } | |
| }; | |
| const validate = validateFormValues(validationSchema); | |
| const MyForm = () => ( | |
| <Form // from react-final-form | |
| onSubmit={onSubmit} | |
| validate={validate} | |
| /> | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment