Blog>
Snippets

Asynchronous Validation in TanStack Forms

Demonstrate implementing asynchronous validation in a form field using TanStack, validating a user's input against a server-side resource.
import { useForm, useField } from '@tanstack/react-form';
Importing required hooks from tanstack/react-form.
async function asyncUsernameValidation(value) {
  return fetch(`/api/validate-username?username=${value}`)
    .then((res) => res.json())
    .then((data) => {
      if (data.exists) return 'Username already exists.';
      return null;
    });
}
Defines an asynchronous function that calls a server-side API to check if the username already exists.
function UsernameField() {
  const { getInputProps } = useField({
    name: 'username',
    validate: asyncUsernameValidation
  });

  return <input {...getInputProps()} placeholder="Username" />;
}
Using the useField hook from TanStack to create a username field with asynchronous validation attached to it.
export default function MyForm() {
  const form = useForm({
    defaultValues: { username: '' },
    onSubmit: async values => {
      // Submit handler here
    }
  });

  return (
    <form.Provider>
      <form onSubmit={form.handleSubmit}>
        <UsernameField />
        <button type="submit">Submit</button>
      </form>
    </form.Provider>
  );
}
The main form component that uses useForm hook to create a form with the UsernameField included.