Skip to content

feat(forms): prevent invalid form submission #62998

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

Merged
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
feat(forms): prevent invalid form submission
Return from `submit()` before running the `action` callback if the form
is invalid. Note that `submit()` will still mark all fields as touched
before returning to ensure that all validation errors are displayed.
  • Loading branch information
leonsenft committed Aug 5, 2025
commit 05d549b3442af664a9c6735268e3886e028081a6
6 changes: 6 additions & 0 deletions packages/forms/experimental/src/api/structure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,12 @@ export async function submit<TValue>(
) {
const node = form() as FieldNode;
markAllAsTouched(node);

// Fail fast if the form is already invalid.
if (node.invalid()) {
return;
}

node.submitState.selfSubmitting.set(true);
try {
const errors = await action(form);
Expand Down
19 changes: 18 additions & 1 deletion packages/forms/experimental/test/node/submit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ import {form, required, submit} from '../../public_api';
import {ValidationError} from '../../src/api/validation_errors';

describe('submit', () => {
it('fails fast on invalid form', async () => {
const data = signal({first: '', last: ''});
const f = form(
data,
(name) => {
required(name.first);
},
{injector: TestBed.inject(Injector)},
);

await submit(f, async (form) => {
fail('Submit action should run not on invalid form');
});

expect(f.first().errors()).toEqual([ValidationError.required()]);
});

it('maps error to a field', async () => {
const data = signal({first: '', last: ''});
const f = form(
Expand Down Expand Up @@ -186,7 +203,7 @@ describe('submit', () => {
expect(submitSpy).toHaveBeenCalledWith('meow');
});

it('recovers from errors throw by submit action', async () => {
it('recovers from errors thrown by submit action', async () => {
const f = form(signal(0), {injector: TestBed.inject(Injector)});
expect(f().submitting()).toBe(false);

Expand Down