-
Notifications
You must be signed in to change notification settings - Fork 145
Open
Description
Environment
- @autoform/react: 4.0.0
- @autoform/yup: 3.0.0
- react-hook-form: 7.68.0
Context
I want to implement real-time validation in AutoForm. I need an isValid state to enable/disable the submit button.
Since @autoform/react doesn't support the mode option, I implemented it manually using onFormInit and form.watch():
export function useAutoFormValidation<T extends FieldValues>(
schemaProvider: SchemaProvider
) {
const [isValid, setIsValid] = useState(false);
const handleFormInit = useCallback(
(form: UseFormReturn<T>) => {
const subscription = form.watch((_, { name }) => {
if (!name) return;
const allValues = form.getValues();
const result = schemaProvider.validateSchema(allValues);
if (result.success) {
form.clearErrors(name);
} else {
const fieldError = result.errors.find(
(err) => err.path.join(".") === name
);
fieldError
? form.setError(name, { message: fieldError.message })
: form.clearErrors(name);
}
setIsValid(result.success);
});
return () => subscription.unsubscribe();
},
[schemaProvider]
);
return { isValid, handleFormInit };
}Problem
This approach causes all input components to re-render on every keystroke, resulting in poor UX (input lag).
Question
Is there a recommended way to implement real-time validation in AutoForm? I'd like to achieve the following while minimizing re-renders:
- Display field-level error messages in real-time
- Enable/disable submit button based on the form's isValid state
Thanks!
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels