Skip to content

Instantly share code, notes, and snippets.

@milantarami
Forked from manzoorwanijk/yup-with-final-form.js
Last active November 3, 2022 09:33
Show Gist options
  • Select an option

  • Save milantarami/dd13e1cf5b7e91e01c641514ff9806ef to your computer and use it in GitHub Desktop.

Select an option

Save milantarami/dd13e1cf5b7e91e01c641514ff9806ef to your computer and use it in GitHub Desktop.
How to properly use yup validation schema with (React) Final Form?
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}
/>
);
// without any library
import { ValidationError } from 'yup';
type ErrorObject = {
[field: string]: string[];
};
/**
* Convert yup error into an error object where the keys are the fields and the values are the errors for that field
* @param {ValidationError} err The yup error to convert
* @returns {ErrorObject} The error object
*/
export function yupErrorToErrorObject(err: ValidationError): ErrorObject {
const object: ErrorObject = {};
err.inner.forEach((x) => {
if (x.path !== undefined) {
object[x.path] = x.errors;
}
});
return object;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment