Blog>
Snippets

Integrating External Validation Libraries with TanStack Form

Example of integrating an external validation library (e.g., Yup) with TanStack Form for complex validation rules, highlighting how to define and apply asynchronous schema validations.
import { useForm } from '@tanstack/react-form';
import * as yup from 'yup';
import { yupValidator } from '@tanstack/yup-form-adapter';
Import necessary modules: useForm from TanStack Form, yup for schema validation, and the yup form adapter.
const schema = yup.object({
  username: yup.string().required('Username is required').email('Enter a valid email'),
  password: yup.string().required('Password is required').min(8, 'Password must be at least 8 characters')
});
Define the validation schema using Yup. This includes two fields: username and password, with rules for each.
const form = useForm({
  defaultValues: { username: '', password: '' },
  validate: yupValidator(schema),
  onSubmit: async (values) => {
    // Handle form submission
    console.log(values);
  }
});
Initialize the form using useForm hook. Default values for the form fields are set, and the Yup validation schema is passed to the form using yupValidator adapter.