Blog>
Snippets

Synchronous Field Validation

Show how to implement synchronous validation for an email field in TanStack Form, including displaying an error message upon invalid input.
import { useForm } from '@tanstack/react-form';

function emailValidator(value) {
  // RegExp for validating email format
  const emailRegex = /^[^@\s]+@[^@\s\.]+\.[^@\s\.]+$/;
  if (!emailRegex.test(value)) {
    return 'Invalid email format';
  }
  return undefined;
}

export function EmailValidationForm() {
  const form = useForm({
    defaultValues: {
      email: '',
    },
    onSubmit: ({ values }) => {
      alert(JSON.stringify(values));
    },
    validate: (values) => {
      const errors = {};
      const emailError = emailValidator(values.email);
      if (emailError) {
        errors.email = emailError;
      }
      return errors;
    }
  });

  return (
    <div>
      <form onSubmit={form.handleSubmit}>
        <div>
          <label>Email</label>
          <input {...form.getFieldProps('email')} />
          {form.touched.email && form.errors.email && <div>{form.errors.email}</div>}
        </div>
        <button type='submit'>Submit</button>
      </form>
    </div>
  );
}
This code snippet demonstrates how to implement synchronous validation for an email field using TanStack Form. The `emailValidator` function checks if the email matches a regular expression for a valid email format. In the form setup (`useForm` hook), the `validate` option is used to apply custom validation logic to the form values, specifically validating the email field. If the email does not match the format, an error message 'Invalid email format' is returned and displayed next to the email field.