Implementing Custom Validation with TanStack Form
Provides an example of adding custom validation logic to form fields using TanStack's utilities, highlighting field-level validation.
import { useForm, useField } from '@tanstack/react-form';
function MyForm() {
const form = useForm({
// Define the initial form state
initialValues: { email: '' },
// Add onSubmit function to handle form submission
onSubmit: async (values) => alert(JSON.stringify(values, null, 2)),
// Define validation logic for the entire form
validate: (values) => {
const errors = {};
if (!values.email) {
// Custom email field validation
errors.email = 'Email is required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {
// Email format validation
errors.email = 'Invalid email address';
}
return errors;
},
});
// Use useField hook to connect your input fields to the form
const emailField = useField({
form,
name: 'email',
});
return (
<form onSubmit={form.handleSubmit}>
<div>
<label>Email</label>
<input type="text" {...emailField.getInputProps()} />
{emailField.meta.error && <span>{emailField.meta.error}</span>}
</div>
<button type="submit">Submit</button>
</form>
);
}
This code snippet creates a simple form with custom validation for an email field using TanStack's React Form library. It demonstrates setting up a form with initial values, a submission handler, and custom validation logic that includes required field validation and email format validation. The useField hook connects the email input field with the form library, allowing for validation and error display.