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
| /** | |
| * If your data contains FieldArray or has nested values, like this | |
| * { | |
| * email: 'email@domain.com', | |
| * shpping: { | |
| * name: 'XYZ', | |
| * phone: { | |
| * code: '+44', | |
| * number: 12345678, | |
| * }, | |
| * address: 'Baker Street', | |
| * zip: 'ABCDEF', | |
| * }, | |
| * billing: { | |
| * name: 'ABC', | |
| * address: 'Some Address', | |
| * zip: 'xyz1234', | |
| * }, | |
| * items: [ | |
| * { | |
| * id: 1234, | |
| * price: 57.9, | |
| * quantity: 2, | |
| * }, | |
| * { | |
| * id: 5678, | |
| * price: 158.2, | |
| * quantity: 1, | |
| * } | |
| * ], | |
| * } | |
| * Here is how to properly make use of yup. | |
| */ | |
| import * as yup from 'yup'; | |
| import { setIn } from 'final-form'; | |
| const validationSchema = yup.object( { | |
| email: yup.string().email(), | |
| shpping: 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 validate = async ( values ) => { | |
| try { | |
| await validationSchema.validate( values, { abortEarly: false } ); | |
| } catch ( err ) { | |
| const errors = err.inner.reduce( ( formError, innerError ) => { | |
| return setIn( formError, innerError.path, innerError.message ); | |
| }, {} ); | |
| return errors; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment