Blog>
Snippets

Custom Validation Logic

Explains how to implement custom validation logic for form fields using the TanStack Form library to enforce complex business rules.
import { useForm } from 'tanstack-react-form';

// Custom validator for an email field
const emailValidator = async (email) => {
  // Regex pattern for validating email format
  const emailPattern = /^\S+@\S+\.\S+$/;
  if (!emailPattern.test(email)) {
    return 'Invalid email format';
  }
  // Simulate an API call to check if the email is already taken
  const isEmailTaken = await fakeApiCheckEmail(email);
  if (isEmailTaken) {
    return 'Email is already taken';
  }
  // Return true for valid emails not taken
  return true;
};

// Simulated API check (replace with real API call)
const fakeApiCheckEmail = async (email) => {
  return email === 'taken@example.com';
};
Defines a custom validation logic for an email field using the TanStack Form library. This involves creating an emailValidator function that validates the email format using a regex pattern and simulates an API call to check if the email is already in use. The function returns a relevant error message if validation fails, or true if the email passes all checks.
const MyForm = () => {
  const form = useForm({
    defaultValues: { email: '' },
    onSubmit: async (values) => {
      console.log('Form submitted with:', values);
    },
    validate: async (values) => {
      const errors = {};
      // Custom validation for the email field
      const emailError = await emailValidator(values.email);
      if (emailError !== true) {
        errors.email = emailError;
      }
      return errors;
    }
  });

  return (
    <form onSubmit={form.handleSubmit}>
      <div>
        <label>Email</label>
        <input {...form.register('email')} />
        {form.errors.email && <p>{form.errors.email}</p>}
      </div>
      <button type='submit'>Submit</button>
    </form>
  );
};
Integrates the custom email validation logic into a form created with the TanStack Form library. This example uses the useForm hook to set up the form, specifying default values, a submit handler, and a validate function that includes the custom email validation. It shows how to use the form's register function to connect an input to the form and display any error messages returned by the custom validation logic.