Blog>
Snippets

Implementing File Validation with TanStack Form

Showcase how to use TanStack Form to implement client-side validation for file size and type before submitting the form.
import { useForm, Controller } from 'tanstack/react-form';
import React from 'react';
Import necessary hooks and components from TanStack Form and React.
const FileUploadForm = () => {
  const { formContext, Controller } = useForm();
  const onSubmit = (data) => console.log(data);
  return (
    <form onSubmit={formContext.handleSubmit(onSubmit)}>
      <Controller
        name="file"
        control={formContext.control}
        rules={{
          validate: {
            size: value => value[0].size < 10000000 || 'File size should be less than 10MB',
            type: value => ['image/jpeg', 'image/png'].includes(value[0].type) || 'Only JPEG or PNG files are allowed'
          }
        }}
        render={({ field }) => <input type="file" {...field} />}
      />
      <button type="submit">Submit</button>
    </form>
  );
};
Define the FileUploadForm component with a file input controlled by TanStack Form. Implement validation rules for file size (less than 10MB) and type (JPEG or PNG only).
export default FileUploadForm;
Export the FileUploadForm component for use in the application.