Blog>
Snippets

Implementing Synchronous Field Validation

Show how to create a custom synchronous validation function for an email field in TanStack Form to ensure proper email format.
const validateEmail = (value) => {
  if (!value.trim()) return 'Email is required.';
  const emailPattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
  if (!emailPattern.test(value)) return 'Invalid email address.';
  return false; // Indicates no error
};
This defines a custom synchronous validation function for an email field. It first checks if the value is non-empty, then validates against an email pattern. If the value doesn't match the pattern, a validation message is returned.
{
  field: 'email',
  validate: validateEmail,
}
This snippet connects the custom validateEmail function with the 'email' field in TanStack Form, enabling the form to validate the email input synchronously as the user types.