Blog>
Snippets

Creating Asynchronous Validation to Check Username Availability

Illustrate checking username availability using asynchronous validation that queries an API endpoint, returning a validation message based on the availability.
const validateUsernameAsync = async (value) => {
  // Call the API to check username availability
  const response = await fetch(`/api/check-username?username=${value}`);
  const { isAvailable } = await response.json();

  // Return an error message if the username is not available
  if (!isAvailable) return 'Username is already taken.';
  return false; // Indicates no error, the username is available
};
This code defines an asynchronous validation function that checks if a username is available. It makes a fetch request to an API endpoint, passing the username as a query parameter. The API is expected to return a JSON object with a boolean property 'isAvailable'. If 'isAvailable' is false, meaning the username is taken, the function returns an error message. Otherwise, it returns false, indicating that there is no validation error and the username is available.
// Within your field component definition
{
  field: 'username',
  validate: validateUsernameAsync
}
This snippet shows how to integrate the asynchronous validation function with a field in TanStack Form. It defines a field component for the username and assigns the 'validateUsernameAsync' function to the 'validate' property of the field configuration. This setup ensures that the asynchronous validation is triggered to check for username availability as part of the form's validation process.