Integrating Yup Validation with TanStack Form
Showcase how to set up form validation using the Yup schema validation library with TanStack Form, covering a common use case of validating a user registration form.
import { useForm, FormProvider, useFormContext } from 'react-tanstack-form';
import * as yup from 'yup';
First, import the necessary modules from react-tanstack-form and Yup for schema validation.
const schema = yup.object().shape({
username: yup.string().required('Username is required').min(5, 'Username must be at least 5 characters'),
email: yup.string().email('Invalid email').required('Email is required'),
password: yup.string().required('Password is required').min(8, 'Password must be at least 8 characters')
});
Define the validation schema using Yup. This schema outlines the rules for the form fields such as username, email, and password.
const useYupValidationResolver = (validationSchema) =>
React.useCallback(
async (data) => {
try {
const values = await validationSchema.validate(data, { abortEarly: false });
return { values, errors: {} };
} catch (errors) {
return {
values: {},
errors: errors.inner.reduce(
(allErrors, currentError) => ({
...allErrors,
[currentError.path]: { type: currentError.type ?? 'validation', message: currentError.message }
}),
{}
)
};
}
},
[validationSchema]
);
Create a custom hook that uses Yup to validate form data. This function tries to validate the data with the schema. If it catches any validation errors, it formats them so that TanStack Form can understand.
const RegistrationForm = () => {
const resolver = useYupValidationResolver(schema);
const methods = useForm({ resolver });
const onSubmit = async (data) => {
console.log(data);
};
return (
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit(onSubmit)}>
<input {...methods.register('username')} placeholder="Enter your username" />
<p>{methods.formState.errors.username?.message}</p>
<input {...methods.register('email')} type="email" placeholder="Enter your email" />
<p>{methods.formState.errors.email?.message}</p>
<input {...methods.register('password')} type="password" placeholder="Enter your password" />
<p>{methods.formState.errors.password?.message}</p>
<button type="submit">Register</button>
</form>
</FormProvider>
);
}
Implement the form using TanStack Form's useForm and FormProvider. Register the form fields and display validation error messages using methods.formState.errors. Submit the form data with the onSubmit handler.