Blog>
Snippets

Implementing Field Validation with useField

Showcase how to implement field validation using the useField hook, including synchronous and asynchronous validation examples.
// Synchronous validation example
const {Field} = useField('email', {
  validate: value => {
    if (!value.includes('@')) {
      return 'Please enter a valid email address.';
    }
  }
});
This code snippet demonstrates synchronous validation for an email field using the useField hook from TanStack Form. It checks if the input value contains an '@' character, returning a validation message if the condition is not met.
// Asynchronous validation example
const {Field} = useField('username', {
  validate: async value => {
    const isUsernameTaken = await checkUsernameAvailability(value); // Hypothetical API call
    if (isUsernameTaken) {
      return 'Username is already taken.';
    }
  }
});
This code snippet shows how to implement asynchronous validation for a username field. It uses an asynchronous function to check if the username is available, leveraging the useField hook. If the username is taken, it returns a validation message.