Skip to content
Merged
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
21 changes: 21 additions & 0 deletions packages/form-state-manager/src/tests/utils/manager-api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1904,4 +1904,25 @@ describe('managerApi', () => {
});
});
});

describe('invalid submit', () => {
it('should not call submit action when invalid + all fields are touched', () => {
const onSubmit = jest.fn();

const managerApi = createManagerApi({ onSubmit });

managerApi().registerField({ name: 'field', validate: () => 'error', render: jest.fn(), internalId: 1 });
managerApi().registerField({ name: 'field2', render: jest.fn(), internalId: 1 });

expect(managerApi().getFieldState('field').touched).toEqual(false);
expect(managerApi().getFieldState('field').touched).toEqual(false);

managerApi().handleSubmit();

expect(managerApi().getFieldState('field').touched).toEqual(true);
expect(managerApi().getFieldState('field').touched).toEqual(true);

expect(onSubmit).not.toHaveBeenCalled();
});
});
});
2 changes: 1 addition & 1 deletion packages/form-state-manager/src/types/form-spy.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Subscription } from './use-subscription';
import { Subscription } from './use-field';
import { ManagerState } from './manager-api';

type Children = (props: ManagerState) => React.ReactElement;
Expand Down
18 changes: 18 additions & 0 deletions packages/form-state-manager/src/utils/manager-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,24 @@ const createManagerApi: CreateManagerApi = ({
function handleSubmit(event?: FormEvent): void {
event && event.preventDefault && event.preventDefault();

if (state.submitting) {
return;
}

if (state.invalid) {
state.registeredFields.forEach((name) => {
setFieldState(name, (state) => ({
...state,
meta: {
...state.meta,
touched: true
}
}));
});

return;
}

let error = false;
state.registeredFields.forEach((name) =>
traverseObject(state.fieldListeners[name].fields, (field) => {
Expand Down