Blog>
Snippets

Creating Custom Validation Rules in TanStack Form

Show how to create and integrate custom validation logic for a field in TanStack Form, using the useForm hook.
import React from 'react';
import { useForm } from '@tanstack/react-form';
Import necessary hooks from TanStack Form and React.
const customValidation = (value) => {
  if (!value) {
    return 'This field is required';
  }
  if (value.length < 5) {
    return 'Value must be at least 5 characters long';
  }
  return undefined;
};
Define a custom validation function to check if the field is filled and its value is at least 5 characters long.
const MyForm = () => {
  const form = useForm({
    initialValues: {
      myField: ''
    },
    validate: (values) => {
      const errors = {};
      errors.myField = customValidation(values.myField);
      return errors;
    }
  });
Set up the form with useForm hook, initializing the 'myField' with an empty string and apply the custom validation defined earlier through the validate option.
  return (
    <form onSubmit={form.handleSubmit()}>
      <input
        {...form.register('myField')}
        type="text"
        placeholder="Enter value"
      />
      {form?.errors?.myField && <div>{form.errors.myField}</div>}
      <button type="submit">Submit</button>
    </form>
  );
};
Render the form in a React component, showing how to use the useForm instance to handle the form submission, register the input field, and display validation errors.
export default MyForm;
Export the form component for use in your application.