Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make validateField return type consistent #4013

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/nine-adults-turn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'formik': patch
---

The validateField function now consistently returns Promise<string | undefined> across all validation paths, where `string` represents a validation error message, `undefined` represents a successful validation.

while previous implementation:
- validation via `<Field validate={...}>` returned Promise<string | undefined>
- validation via schema returned Promise<void>
2 changes: 1 addition & 1 deletion docs/api/formik.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ component.

Imperatively call your `validate` or `validateSchema` depending on what was specified. You can optionally pass values to validate against and this modify Formik state accordingly, otherwise this will use the current `values` of the form.

#### `validateField: (field: string) => void`
#### `validateField: (field: string) => Promise<string | undefined>`

Imperatively call field's `validate` function if specified for given field or run schema validation using [Yup's `schema.validateAt`](https://github.com/jquense/yup#mixedvalidateatpath-string-value-any-options-object-promiseany-validationerror) and the provided top-level `validationSchema` prop. Formik will use the current field value.

Expand Down
12 changes: 7 additions & 5 deletions packages/formik/src/Formik.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -484,11 +484,10 @@ export function useFormik<Values extends FormikValues = FormikValues>({
}
}, [enableReinitialize, props.initialStatus, props.initialTouched]);

const validateField = useEventCallback((name: string) => {
const validateField = useEventCallback((name: string): Promise<string | undefined> => {
// This will efficiently validate a single field by avoiding state
// changes if the validation function is synchronous. It's different from
// what is called when using validateForm.

if (
fieldRegistry.current[name] &&
isFunction(fieldRegistry.current[name].validate)
Expand All @@ -506,6 +505,7 @@ export function useFormik<Values extends FormikValues = FormikValues>({
payload: { field: name, value: error },
});
dispatch({ type: 'SET_ISVALIDATING', payload: false });
return error;
});
} else {
dispatch({
Expand All @@ -522,15 +522,17 @@ export function useFormik<Values extends FormikValues = FormikValues>({
return runValidationSchema(state.values, name)
.then((x: any) => x)
.then((error: any) => {
const fieldError = getIn(error, name);
dispatch({
type: 'SET_FIELD_ERROR',
payload: { field: name, value: getIn(error, name) },
payload: { field: name, value: fieldError },
});
dispatch({ type: 'SET_ISVALIDATING', payload: false });
});
return fieldError
})
}

return Promise.resolve();
return Promise.resolve(undefined);
});

const registerField = React.useCallback((name: string, { validate }: any) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/formik/src/types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export interface FormikHelpers<Values> {
/** Validate form values */
validateForm: (values?: any) => Promise<FormikErrors<Values>>;
/** Validate field value */
validateField: (field: string) => Promise<void> | Promise<string | undefined>;
validateField: (field: string) => Promise<string | undefined>;
/** Reset form */
resetForm: (nextState?: Partial<FormikState<Values>>) => void;
/** Submit the form imperatively */
Expand Down
34 changes: 19 additions & 15 deletions packages/formik/test/Field.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -385,15 +385,16 @@ describe('Field / FastField', () => {
component: 'input',
});
rerender();

act(() => {
getFormProps().validateField('name');
const error = await act(async () => {
return await getFormProps().validateField('name');
});

rerender();
await waitFor(() => {
expect(validate).toHaveBeenCalled();
expect(getFormProps().errors.name).toBe('Error!');
expect(error).toBe('Error!');
});
}
);
Expand All @@ -408,12 +409,15 @@ describe('Field / FastField', () => {
// workaround for `useEffect` to run: https://github.com/facebook/react/issues/14050
rerender();

act(() => {
getFormProps().validateField('name');
const error = await act(async () => {
return await getFormProps().validateField('name');
});

expect(validate).toHaveBeenCalled();
await waitFor(() => expect(getFormProps().errors.name).toBe('Error!'));
await waitFor(() => {
expect(getFormProps().errors.name).toBe('Error!')
expect(error).toBe('Error!')
});
}
);

Expand All @@ -432,15 +436,16 @@ describe('Field / FastField', () => {

rerender();

act(() => {
getFormProps().validateField('name');
const error = await act(async () => {
return await getFormProps().validateField('name');
});

await waitFor(() =>
await waitFor(() => {
expect(getFormProps().errors).toEqual({
name: errorMessage,
})
);
expect(error).toBe(errorMessage)
});
}
);

Expand All @@ -460,13 +465,12 @@ describe('Field / FastField', () => {

rerender();

act(() => {
getFormProps().validateField('user.name');
});
const error = await act(async () => await getFormProps().validateField('user.name'));

await waitFor(() =>
await waitFor(() => {
expect(getFormProps().errors).toEqual({ user: { name: 'required' } })
);
expect(error).toBe('required')
});
}
);
});
Expand Down