Adding Custom Validation Rules in TanStack Form
Illustrate adding custom validation logic to a form field in TanStack Form, such as validating an email address format.
import { useForm, useField } from 'tanstack-react-form';
First, import `useForm` and `useField` from 'tanstack-react-form' to use form and field hooks.
const emailValidationFn = (value) => (/^\w+([\.-]?\w+)*@\w+([\.:]?\w+)*(\.\w{2,3})+$/.test(value) ? false : 'Invalid email address');
Define a custom email validation function. It returns 'Invalid email address' if the input does not match the regex for a valid email.
function EmailForm() {
const { Form } = useForm({
onSubmit: async (values) => {
console.log(values);
},
defaultValues: {
email: '',
},
});
const { getInputProps } = useField('email', {
validate: emailValidationFn,
});
return (
<Form>
<input {...getInputProps()} type="email" />
<button type="submit">Submit</button>
</Form>
);
}
Create a form component using `useForm` and use `useField` for the email field. Attach the custom `emailValidationFn` for the email field to validate the email address format. The form will display an input field for email and a submit button.