Implementing Custom Synchronous Validation
Showcase creating a custom validation function for an email field that synchronously checks if the email format is correct using TanStack Form.
import { useForm, useField } from 'tanstack/react-form';
const emailValidator = (value) => {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!regex.test(value)) {
return 'Invalid email format';
}
return false; // No error
};
First, we are importing necessary functions from TanStack Form. Then, we define a 'emailValidator' function that uses a regular expression to check if the email format is correct. If the format is incorrect, it returns an error message; otherwise, it returns false indicating no error.
const MyForm = () => {
const form = useForm({
defaultValues: { email: '' },
validate: (values) => {
const errors = {};
const emailError = emailValidator(values.email);
if (emailError) errors.email = emailError;
return errors;
}
});
const emailField = useField('email', form);
return (
<form>
<input {...emailField.getInputProps()} />
{emailField.meta.error && <div>{emailField.meta.error}</div>}
</form>
);
}
Here, we define a 'MyForm' component that uses TanStack Form to create a form with an email field. We call 'useForm' with a validation function that utilizes our 'emailValidator'. It checks the email field for any errors. If found, it assigns the error message to the field error state. The useField hook is then used to connect the email input field to the form state and validation logic. If there's an error, it is displayed below the input field.