Blog>
Snippets

Custom Validation and Error Messaging

Explain how to create custom validation functions and display error messages for form fields using TanStack Form, focusing on enhancing the user experience with meaningful feedback.
import { useForm } from '@tanstack/react-form';

function validateEmail(value) {
  if (!value) {
    return 'Email is required';
  }
  if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
    return 'Invalid email address';
  }
  return false;
}
Defines a custom validation function `validateEmail` for checking if the email field is filled and has a valid email format. If the check fails, it returns a corresponding error message.
function MyForm() {
  const form = useForm({
    defaultValues: {
      email: '',
    },
    onSubmit: async values => {
      // Form submission logic
    },
    validate: values => {
      const errors = {};
      const emailError = validateEmail(values.email);
      if (emailError) {
        errors.email = emailError;
      }
      return errors;
    }
  });

  return (
    <form onSubmit={form.handleSubmit}>
      <input {...form.fields.email.getInputProps()} />
      {form.fields.email.error && <div>{form.fields.email.error}</div>}
    </form>
  );
}
Integrates the custom `validateEmail` function into a form using TanStack Form. It assigns the `validate` method to check for errors and conditionally renders error messages right next to the input field if any are present.