Implementing Custom Validation Rules with TanStack Form
Provide an example of how to implement custom validation logic for form fields in TanStack Form, including both synchronous and asynchronous examples.
const validateSync = (value) => {
if (!value) return 'Field is required';
if (value.length < 5) return 'Value must be at least 5 characters';
return false; // Indicates valid input
};
This code demonstrates synchronous custom validation for a form field using TanStack Form. It checks if the field is not empty and if the input has at least 5 characters. The function returns a validation error message if the input fails the checks; otherwise, it returns false, indicating the input is valid.
const validateAsync = async (value) => {
if (!value) return 'Field is required';
// Simulating an API call with setTimeout
return new Promise((resolve) => {
setTimeout(() => {
if (value === 'uniqueValue') resolve(false); // false indicates no error
else resolve('Value must be unique');
}, 1000);
});
};
This snippet illustrates asynchronous custom validation for a form field. It performs a simulated asynchronous operation (e.g., checking for uniqueness against a server-side resource) using JavaScript's `setTimeout`. The validation is considered successful (i.e., returns false) if the field's value is 'uniqueValue'; otherwise, it returns an error message.