Implementing Asynchronous Validation in TanStack Form
Provide an example of how to carry out asynchronous validation in TanStack Form, such as validating an email address against a database, including handling the loading state and displaying validation messages.
import { useForm, useAsyncValidation } from 'tanstack-form';
Imports useForm and useAsyncValidation hooks from TanStack Form.
const emailAsyncValidator = async (email) => {\n // Simulate an API call to validate the email\n const response = await fetch(`/api/validate-email?email=${email}`);\n const data = await response.json();\n if (!data.isValid) {\n return 'Email is already in use';\n }\n return null;\n};
Defines an asynchronous validator function for the email field that queries an imaginary API endpoint to check if the email is already in use. Returns a validation message if invalid, otherwise null.
function MyForm() {\n const {\n Form,\n isSubmitting,\n values,\n getFieldProps,\n errors\n } = useForm({\n initialValues: { email: '' },\n onSubmit: async (values) => {\n await submitForm(values);\n }\n });\n\n useAsyncValidation({\n name: 'email',\n validator: emailAsyncValidator,\n debounceInterval: 500 // Optionally debounce the validation\n });\n\n return (<form onSubmit={Form.handleSubmit}>\n <input type='email' {...getFieldProps('email')} placeholder='Enter your email' />\n {errors.email && <div>{errors.email}</div>}\n <button type='submit' disabled={isSubmitting}>Submit</button>\n {isSubmitting && <div>Loading...</div>}\n </form>);\n}
Creates a form component using TanStack Form with an email input. It sets up asynchronous validation for the email field using the emailAsyncValidator function. It displays loading state and validation messages.