Skip to content

Instantly share code, notes, and snippets.

@manzoorwanijk
Last active August 22, 2024 11:44
Show Gist options
  • Save manzoorwanijk/5993a520f2ac7890c3b46f70f6818e0a to your computer and use it in GitHub Desktop.
Save manzoorwanijk/5993a520f2ac7890c3b46f70f6818e0a 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}
/>
);
@shifoc
Copy link

shifoc commented Aug 22, 2024

with typescript resolver

import { setIn } from "final-form";
import { AnySchema, ValidationError } from "yup";

export function yupResolver(schema: AnySchema) {
	return async (value: object) => {
		try {
			await schema.validate(value, { abortEarly: false });
		} catch (error) {
			if (error instanceof ValidationError) {
				return error.inner.reduce((errors, error: ValidationError) => {
					const path = error.path ?? "global";
					return setIn(errors, path, error.message);
				}, {});
			}

			throw error;
		}
	};
}
<Form
	onSubmit={(fields) => console.log(fields)}
	validate={yupResolver(SupplierSchema)}...

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment