Skip to content

Commit

Permalink
feat: added error display form util
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Aug 4, 2024
1 parent c4f7f72 commit b439d5e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/core/src/form/useForm.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,17 @@ describe('validation', () => {
expect(screen.getByTestId('form-err').textContent).toBe('Constraints not satisfied');
});

test('displays errors if the field is touched', async () => {
const { setFieldTouched, displayError, setFieldErrors } = await renderSetup(() => {
return useForm();
});

setFieldErrors('test', 'error');
expect(displayError('test')).toBeUndefined();
setFieldTouched('test', true);
expect(displayError('test')).toBe('error');
});

test('updates the form isValid', async () => {
const input = ref<HTMLInputElement>();

Expand Down
5 changes: 5 additions & 0 deletions packages/core/src/form/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ export function useForm<TForm extends FormObject = FormObject, TOutput extends F
return ctx.getFieldErrors(path)[0];
}

function displayError(path: Path<TForm>) {
return ctx.isFieldTouched(path) ? getError(path) : undefined;
}

provide(FormKey, {
...ctx,
...transactionsManager,
Expand All @@ -103,6 +107,7 @@ export function useForm<TForm extends FormObject = FormObject, TOutput extends F
setFieldErrors: ctx.setFieldErrors,
setValues: ctx.setValues,
getError,
displayError,
...actions,
};
}

0 comments on commit b439d5e

Please sign in to comment.