fix(form-core): prevent removeValue from auto-touching shifted siblings #2133
main fromrefs/pull/2133/head·opened What changed#
In validateArrayFieldsStartingFrom, fields with an existing instance now call fieldInstance.validate(cause) directly instead of going through this.validateField(). This avoids the auto-touch side-effect in validateField that marks fields as touched even when the user never interacted with them.
Why#
Calling form.removeValue(index) on an array field was flipping isTouched to true on every sibling at index ≥ removed index. The bug lives in validateField which auto-touches any field that has an instance but isn't yet touched.
How to reproduce#
- Create a form with an array field
- Call
form.removeValue(0)without interacting with other fields - Observe that
isTouchedbecomestrueon all shifted siblings
Closes #2131
Summary by CodeRabbit#
- Bug Fixes
- Improved validation behavior for array fields so removing or reordering items no longer incorrectly marks sibling fields as “touched.”
- Preserves fields' prior touched state when validating already-mounted nested fields, reducing unexpected validation side effects during array operations.
- 1
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed. Inline comments: In `@packages/form-core/src/FormApi.ts`: - Around line 1608-1616: The current code calls fieldInstance.validate(cause) which avoids auto-touching but relies on FieldApi.validate returning [] when meta.isTouched is false, leaving shifted untouched siblings unvalidated; change this by adding an internal "validate without touching" path: extend validateField to accept an options flag (e.g., { touch?: boolean }) or add a new internal method (e.g., validateFieldInternal/FieldApi.validateWithoutTouch) that runs the same validation logic regardless of meta.isTouched but does not mutate touch state, then replace the direct call to fieldInstance.validate(cause) with a call to validateField(nestedField, cause, { touch: false }) or the new internal method so shifted siblings revalidate without auto-touch side effects; update FieldApi.validate to delegate to the shared internal validator to avoid duplication.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
d506b7d4-0546-43d1-a8b3-a5847867e52b📥 Commits
Reviewing files that changed from the base of the PR and between 254f157e72df15e07fb1f2250cab3110b7f2762d and cd491bac6c8d55908a0dcf6f51701a18eb1300b3.
📒 Files selected for processing (1)
packages/form-core/src/FormApi.ts
@@ -1605,4 +1605,12 @@16051605 batch(() => {16061606 fieldsToValidate.forEach((nestedField) => {16071607 fieldValidationPromises.push(1608- Promise.resolve().then(() => this.validateField(nestedField, cause)),1608+ Promise.resolve().then(() => {1609+ // If the field instance already exists, call validate directly1610+ // to avoid auto-touching shifted siblings1611+ const fieldInstance = this.fieldInfo[nestedField]?.instance1612+ if (fieldInstance) {1613+ return fieldInstance.validate(cause)1614+ }1615+ return this.validateField(nestedField, cause)1616+ }),⚠️ Potential issue | 🟠 Major
Preserve validation when bypassing auto-touch.
Calling
fieldInstance.validate(cause)directly skips validation for untouched fields becauseFieldApi.validatereturns[]whenmeta.isTouchedis false (packages/form-core/src/FieldApi.ts:1991-1997). This fixes the touched mutation, but shifted untouched siblings will no longer revalidate, leaving stale field errors possible after insert/remove/replace.Consider adding an internal “validate without touching” path instead of calling
FieldApi.validateas-is.Possible direction
- if (fieldInstance) { - return fieldInstance.validate(cause) - } - return this.validateField(nestedField, cause) + return this.validateField(nestedField, cause, { + touch: false, + })This would require extending
validateFieldto make theisTouchedmutation optional while still running the same validation logic.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/form-core/src/FormApi.ts` around lines 1608 - 1616, The current code calls fieldInstance.validate(cause) which avoids auto-touching but relies on FieldApi.validate returning [] when meta.isTouched is false, leaving shifted untouched siblings unvalidated; change this by adding an internal "validate without touching" path: extend validateField to accept an options flag (e.g., { touch?: boolean }) or add a new internal method (e.g., validateFieldInternal/FieldApi.validateWithoutTouch) that runs the same validation logic regardless of meta.isTouched but does not mutate touch state, then replace the direct call to fieldInstance.validate(cause) with a call to validateField(nestedField, cause, { touch: false }) or the new internal method so shifted siblings revalidate without auto-touch side effects; update FieldApi.validate to delegate to the shared internal validator to avoid duplication.✅ Addressed in commit a1294aa
View your CI Pipeline Execution ↗ for commit a1294aad6abbe8918e23178dddec575811811f47
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 1m 31s View ↗ nx run-many --target=build --exclude=examples/**✅ Succeeded 32s View ↗
☁️ Nx Cloud last updated this comment at
2026-04-29 13:45:07UTCMore templates
- @tanstack/form-example-angular-array
- @tanstack/form-example-angular-large-form
- @tanstack/form-example-angular-simple
- @tanstack/form-example-angular-standard-schema
- @tanstack/form-example-lit-array
- @tanstack/form-example-lit-simple
- @tanstack/form-example-lit-standard-schema
- @tanstack/form-example-lit-ui-libraries
- @tanstack/form-example-react-array
- @tanstack/form-example-react-compiler
- @tanstack/form-example-react-composition
- @tanstack/form-example-react-devtools
- @tanstack/form-example-react-dynamic
- @tanstack/field-errors-from-form-validators
- @tanstack/form-example-react-large-form
- @tanstack/form-example-react-next-server-actions
- @tanstack/form-example-react-next-server-actions-zod
- @tanstack/form-example-react-query-integration
- @tanstack/form-example-remix
- @tanstack/form-example-react-simple
- @tanstack/form-example-react-standard-schema
- @tanstack/form-example-react-tanstack-start
- @tanstack/form-example-react-ui-libraries
- @tanstack/form-example-solid-array
- @tanstack/form-example-solid-devtools
- @tanstack/form-example-solid-large-form
- @tanstack/form-example-solid-simple
- @tanstack/form-example-solid-standard-schema
- @tanstack/form-example-vue-array
- @tanstack/form-example-vue-simple
- @tanstack/form-example-vue-standard-schema
- @tanstack/form-example-svelte-array
- @tanstack/form-example-svelte-large-form
- @tanstack/form-example-svelte-simple
- @tanstack/form-example-svelte-standard-schema
@tanstack/angular-form
npm i https://pkg.pr.new/@tanstack/angular-form@2133@tanstack/form-core
npm i https://pkg.pr.new/@tanstack/form-core@2133@tanstack/form-devtools
npm i https://pkg.pr.new/@tanstack/form-devtools@2133@tanstack/lit-form
npm i https://pkg.pr.new/@tanstack/lit-form@2133@tanstack/react-form
npm i https://pkg.pr.new/@tanstack/react-form@2133@tanstack/react-form-devtools
npm i https://pkg.pr.new/@tanstack/react-form-devtools@2133@tanstack/react-form-nextjs
npm i https://pkg.pr.new/@tanstack/react-form-nextjs@2133@tanstack/react-form-remix
npm i https://pkg.pr.new/@tanstack/react-form-remix@2133@tanstack/react-form-start
npm i https://pkg.pr.new/@tanstack/react-form-start@2133@tanstack/solid-form
npm i https://pkg.pr.new/@tanstack/solid-form@2133@tanstack/solid-form-devtools
npm i https://pkg.pr.new/@tanstack/solid-form-devtools@2133@tanstack/svelte-form
npm i https://pkg.pr.new/@tanstack/svelte-form@2133@tanstack/vue-form
npm i https://pkg.pr.new/@tanstack/vue-form@2133commit:
a1294aaActionable comments posted: 1
🧹 Nitpick comments (1)
packages/form-core/src/FormApi.ts (1)
1579-1586:FieldGroupApi.validateArrayFieldsStartingFromdoes not forwardoptions.Per
packages/form-core/src/FieldGroupApi.ts:310-324, theFieldGroupApiwrapper delegates tothis.form.validateArrayFieldsStartingFrom(name, index, cause)without a 4th argument. Any caller (internal or external) going through a FieldGroup will silently loseavoidTouch, so if this helper is ever invoked from a FieldGroup-scoped removal path it will regress to the old auto-touch behavior. Update FieldGroupApi's signature and forwardoptionsfor parity.validateArrayFieldsStartingFrom = async < TField extends DeepKeysOfType<TFieldGroupData, any[]>, >( field: TField, index: number, cause: ValidationCause, + options?: { avoidTouch?: boolean }, ) => { return this.form.validateArrayFieldsStartingFrom( this.getFormFieldName(field), index, cause, + options, ) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/form-core/src/FormApi.ts` around lines 1579 - 1586, The FieldGroupApi.validateArrayFieldsStartingFrom wrapper currently omits the options parameter so avoidTouch is lost; update FieldGroupApi's method signature to accept the fourth parameter (options?: { avoidTouch?: boolean }) and forward it when calling this.form.validateArrayFieldsStartingFrom(name, index, cause, options) so callers via FieldGroup retain avoidTouch behavior—ensure the method declaration and the delegated call both include the options parameter and types match the FormApi.validateArrayFieldsStartingFrom signature.🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed. Inline comments: In `@packages/form-core/src/FormApi.ts`: - Around line 1609-1634: The temporary-touch logic inside the Promise.resolve block when options?.avoidTouch is true should ensure the original isTouched is always restored even if fieldInstance.validate(cause) throws or rejects: wrap the validate call and the second setMeta restoration in a try/finally so that after temporarily setting fieldInstance.setMeta(... isTouched: true) you always run the restore setMeta(...) in the finally block; keep the early-return of the validate result, and otherwise fall back to this.validateField(nestedField, cause). Reference the Promise.resolve(...) block, options?.avoidTouch, fieldInstance, fieldInstance.validate(cause), and fieldInstance.setMeta(...) when making the change. --- Nitpick comments: In `@packages/form-core/src/FormApi.ts`: - Around line 1579-1586: The FieldGroupApi.validateArrayFieldsStartingFrom wrapper currently omits the options parameter so avoidTouch is lost; update FieldGroupApi's method signature to accept the fourth parameter (options?: { avoidTouch?: boolean }) and forward it when calling this.form.validateArrayFieldsStartingFrom(name, index, cause, options) so callers via FieldGroup retain avoidTouch behavior—ensure the method declaration and the delegated call both include the options parameter and types match the FormApi.validateArrayFieldsStartingFrom signature.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
e842bc31-0829-4659-8dff-b4c5f0928b2e📥 Commits
Reviewing files that changed from the base of the PR and between cd491bac6c8d55908a0dcf6f51701a18eb1300b3 and a1294aad6abbe8918e23178dddec575811811f47.
📒 Files selected for processing (1)
packages/form-core/src/FormApi.ts
packages/form-core/src/FormApi.ts lines 1609 to 1634@@ -1608,0 +1614,21 @@1614+ if (fieldInstance) {1615+ const wasTouched = fieldInstance.state.meta.isTouched1616+ if (!wasTouched) {1617+ // Temporarily touch the field so validation runs, then restore1618+ fieldInstance.setMeta((prev) => ({1619+ ...prev,1620+ isTouched: true,1621+ }))1622+ }1623+ const result = await fieldInstance.validate(cause)1624+ if (!wasTouched) {1625+ fieldInstance.setMeta((prev) => ({1626+ ...prev,1627+ isTouched: false,1628+ }))1629+ }1630+ return result1631+ }1632+ }1633+ return this.validateField(nestedField, cause)1634+ }),⚠️ Potential issue | 🟠 Major
Guard restoration with try/finally, and note the transient-state exposure.
Two concerns with the temporary-touch approach:
- No error safety. If
fieldInstance.validate(cause)throws (sync throw before returning a Promise, or a rejected Promise returned synchronously before theawait), the secondsetMetanever runs and the field is left permanentlyisTouched: true— reintroducing the exact bug this PR fixes. Wrap intry/finally. - Observable transient state. Between the two
setMetacalls, the derived stores (fieldMetaDerived,store.isTouched, devtools broadcast viathrottleFormState) momentarily reflectisTouched: truefor every untouched sibling. With N shifted siblings all toggling in parallel, subscribers/listeners can observe a spurious "all touched" window. Also, if the user genuinely touches the field during theawait, the restoration will clobber their touch back tofalse.
The
try/finallyis a strict correctness fix and should be applied. The transient-state issue is the main reason the originally suggested refactor (an internal{ touch: false }path onvalidateFieldthat skips theisTouchedcheck entirely) is cleaner — worth reconsidering as a follow-up.🛡️ Proposed fix: ensure restoration on error paths
if (options?.avoidTouch) { const fieldInstance = this.fieldInfo[nestedField]?.instance if (fieldInstance) { const wasTouched = fieldInstance.state.meta.isTouched if (!wasTouched) { // Temporarily touch the field so validation runs, then restore fieldInstance.setMeta((prev) => ({ ...prev, isTouched: true, })) } - const result = await fieldInstance.validate(cause) - if (!wasTouched) { - fieldInstance.setMeta((prev) => ({ - ...prev, - isTouched: false, - })) - } - return result + try { + return await fieldInstance.validate(cause) + } finally { + if (!wasTouched) { + fieldInstance.setMeta((prev) => ({ + ...prev, + isTouched: false, + })) + } + } } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/form-core/src/FormApi.ts` around lines 1609 - 1634, The temporary-touch logic inside the Promise.resolve block when options?.avoidTouch is true should ensure the original isTouched is always restored even if fieldInstance.validate(cause) throws or rejects: wrap the validate call and the second setMeta restoration in a try/finally so that after temporarily setting fieldInstance.setMeta(... isTouched: true) you always run the restore setMeta(...) in the finally block; keep the early-return of the validate result, and otherwise fall back to this.validateField(nestedField, cause). Reference the Promise.resolve(...) block, options?.avoidTouch, fieldInstance, fieldInstance.validate(cause), and fieldInstance.setMeta(...) when making the change.Codecov Report#
:white_check_mark: All modified and coverable lines are covered by tests. :white_check_mark: Project coverage is 90.31%. Comparing base (
6892ed0) to head (a1294aa). :warning: Report is 170 commits behind head on main.Additional details and impacted files
@@ Coverage Diff @@ ## main #2133 +/- ## ========================================== - Coverage 90.35% 90.31% -0.05% ========================================== Files 38 49 +11 Lines 1752 2054 +302 Branches 444 536 +92 ========================================== + Hits 1583 1855 +272 - Misses 149 179 +30 Partials 20 20:umbrella: View full report in Codecov by Sentry. :loudspeaker: Have feedback on the report? Share it here.
:rocket: New features to boost your workflow:
- :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
- :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
Hmm ... this has probably been here for a long while, but you're right that it makes little sense to touch the fields. However, the implementation seems to either be overcomplicated for it, or more likely, it should target a different function of the library.
I'll look into it and let you know.
Closing due to inactivity. As noted, the implementation may be overcomplicated for the change. Happy to reopen with a simpler approach.
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
validateArrayFieldsStartingFrominFormApi.tsnow accepts an optionaloptions?: { avoidTouch?: boolean }. WhenavoidTouchis true, and a mountedFieldApiinstance exists for a nested field, validation is performed viafieldInstance.validate(cause)while preserving priormeta.isTouchedstate; otherwise it falls back tovalidateField.removeFieldValuenow calls this with{ avoidTouch: true }after array validation at'change'.Changes#
packages/form-core/src/FormApi.tsoptions?: { avoidTouch?: boolean }tovalidateArrayFieldsStartingFrom; whenavoidTouchis true, preferfieldInstance.validate(cause)for mounted fields and preserveisTouchedduring validation.removeFieldValuenow callsvalidateArrayFieldsStartingFrom(..., { avoidTouch: true })after validating the array at'change'to avoid touching shifted siblings.Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem#
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
#2131by calling fieldInstance.validate() directly to avoid the auto-touch behavior in validateField().✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share