Skip to content
Source
Sign inSign up
TanStack/form

fix: sync validation errors for delayed-mounted fields #1691

Mergedjiji-hoon96(GitHub profile, opens in a new tab)merged 20 commits intomain fromrefs/pull/1691/headmerged by LeCarbonator(GitHub profile, opens in a new tab)

Fixes validation errors not appearing on fields that mount after form initialization

Problem

When fields are mounted after the form's initial validation runs, validation errors from form-level validators (like [onMount]) are not displayed on these delayed fields, leading to inconsistent validation UX.

Solution

  • FormApi: Store all field errors (including for unmounted fields) in _allFieldErrors state
  • FieldApi: Sync existing errors from form state when fields mount, marking them as originating from form validation

Changes

  • Added _allFieldErrors property to BaseFormState to persist validation errors for all fields
  • Modified validateSync to store field errors for both mounted and unmounted fields
  • Enhanced FieldApi.mount() to sync existing errors from form state on field mount
  • Added comprehensive tests covering delayed mount, multiple fields, and remount scenarios

Closes #1630

    1. @LeCarbonator I thought this issue needed to be resolved promptly, and I'm curious to hear your thoughts on the matter.

    2. I'm also quite curious about this one. I've had to use hidden in all of my forms, rather than conditional rendering. Which doesn't feel great—especially for future readers of the code.

    3. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 23bfa578ed45ee64dc2544aa74fa988ddce95c4c

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded57sView ↗
      nx run-many --target=build --exclude=examples/**✅ Succeeded<1sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-12-18 10:09:17 UTC

    4. I'm just not sure if this is the way to go about it. I've been tinkering behind the scenes to see what truly causes this, but I suppose I should focus more on it so it can get fixed

    5. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented
      More templates

      @tanstack/angular-form

      npm i https://pkg.pr.new/@tanstack/angular-form@1691

      @tanstack/form-core

      npm i https://pkg.pr.new/@tanstack/form-core@1691

      @tanstack/form-devtools

      npm i https://pkg.pr.new/@tanstack/form-devtools@1691

      @tanstack/lit-form

      npm i https://pkg.pr.new/@tanstack/lit-form@1691

      @tanstack/react-form

      npm i https://pkg.pr.new/@tanstack/react-form@1691

      @tanstack/react-form-devtools

      npm i https://pkg.pr.new/@tanstack/react-form-devtools@1691

      @tanstack/react-form-nextjs

      npm i https://pkg.pr.new/@tanstack/react-form-nextjs@1691

      @tanstack/react-form-remix

      npm i https://pkg.pr.new/@tanstack/react-form-remix@1691

      @tanstack/react-form-start

      npm i https://pkg.pr.new/@tanstack/react-form-start@1691

      @tanstack/solid-form

      npm i https://pkg.pr.new/@tanstack/solid-form@1691

      @tanstack/solid-form-devtools

      npm i https://pkg.pr.new/@tanstack/solid-form-devtools@1691

      @tanstack/svelte-form

      npm i https://pkg.pr.new/@tanstack/svelte-form@1691

      @tanstack/vue-form

      npm i https://pkg.pr.new/@tanstack/vue-form@1691

      commit: 23bfa57

    6. codecov[bot](GitHub profile, opens in a new tab)commented

      Codecov Report

      :white_check_mark: All modified and coverable lines are covered by tests. :white_check_mark: Project coverage is 89.43%. Comparing base (6892ed0) to head (23bfa57). :warning: Report is 102 commits behind head on main.

      Additional details and impacted files
      @@            Coverage Diff             @@
      ##             main    #1691      +/-   ##
      ==========================================
      - Coverage   90.35%   89.43%   -0.93%     
      ==========================================
        Files          38       48      +10     
        Lines        1752     1940     +188     
        Branches      444      487      +43     
      ==========================================
      + Hits         1583     1735     +152     
      - Misses        149      184      +35     
      - Partials       20       21       +1     

      :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.
  • jiji-hoon96(GitHub profile, opens in a new tab)commented

    I'm not entirely sure why the delayed-mounted field isn't receiving form validation either.

    While my proposed method could resolve it, errors exist in both fieldMeta and _allFieldErrors. This raises concerns about duplicate states and memory overhead issues, as it would persistently store errors for all unmounted fields.

    If you have any ideas, please share them so we can explore them together.

    I have three potential approaches in mind

    1. Event-driven approach: Re-trigger form validation when the field mounts, re-executing the validation results only for this field.
    2. Store validation results as a function and evaluate them when needed.
    3. Subscribe to the form's validation state when the field mounts.
  • The issue is that while mapping form validators to respective fields, it only iterates through the existing record of (previously registered) fields. Ideally, it should have the following behaviour:

    • If a field error does not have an entry in the fieldInfo record, create one
    • If deleteField or removeValue is called, it should remove that entry
  • @LeCarbonator FormApi has been improved with a comprehensive error-handling approach that includes all field errors, and features have been added to automatically generate fieldInfo and prevent memory leaks in the deleteField method.

  • @jiji-hoon96 does this mean the issue should be resolved?

  • changeset-bot[bot](GitHub profile, opens in a new tab)commented

    🦋 Changeset detected

    Latest commit: 23bfa578ed45ee64dc2544aa74fa988ddce95c4c

    The changes in this PR will be included in the next version bump.

    This PR includes changesets to release 13 packages
    NameType
    @tanstack/form-corePatch
    @tanstack/angular-formPatch
    @tanstack/form-devtoolsPatch
    @tanstack/lit-formPatch
    @tanstack/react-formPatch
    @tanstack/solid-formPatch
    @tanstack/svelte-formPatch
    @tanstack/vue-formPatch
    @tanstack/react-form-devtoolsPatch
    @tanstack/solid-form-devtoolsPatch
    @tanstack/react-form-nextjsPatch
    @tanstack/react-form-remixPatch
    @tanstack/react-form-startPatch

    Not sure what this means? Click here to learn what changesets are.

    Click here if you're a maintainer who wants to add another changeset to this PR

  • Thanks for the PR! This is pretty close, but there are some things to address. If you'd like, I can help out with addressing them.

    @@ -1537,0 +1548,21 @@
    1548+ ...allFieldErrors[typedFieldName],
    1549+ [errorMapKey]: fieldError,
    1550+ }
    1551+ }
    1552+ }
    1553+ this.baseStore.setState((prev) => ({
    1554+ ...prev,
    1555+ _allFieldErrors: allFieldErrors,
    1556+ }))
    1557+ }
    1558+
    1559+ const allFieldsToProcess = new Set([
    1560+ ...Object.keys(this.state.fieldMeta),
    1561+ ...Object.keys(fieldErrors || {}),
    1562+ ] as DeepKeys<TFormData>[])
    1563+
    1564+ for (const field of allFieldsToProcess) {
    1565+ if (fieldErrors?.[field] && !this.fieldInfo[field]) {
    1566+ this.getFieldInfo(field)
    1567+ }
    1568+
    LeCarbonator(GitHub profile, opens in a new tab)commented

    This is going in the right direction, but _allFieldErrors is not the way. Iterating over previously mounted fields in fieldMeta is not enough for validation errors (like you correctly asserted), so ones that are missing should be added to it.

    Fields derive their data from fieldMeta, so if they were added here, they would have the data not just on mount, but on construction.

    One issue that we might run into with this approach is that wrong field names can result in a locked state. There is no field to read the stored error, so it is never visually shown. I don't think that's an issue because:

    • Our standard schemas are type safe when it comes to keys.
    • Standard schemas send a copy of the error list to the form error state, so it can be figured out if there's an issue.

    Overall, I think the right way to go is to add missing fieldMeta from field errors if they're not present. Use the default field meta state for the other props being added.

    jiji-hoon96(GitHub profile, opens in a new tab)commented

    Thank you for the detailed feedback! You're absolutely right. I've refactored the implementation to use fieldMeta instead of _allFieldErrors.

    LeCarbonator(GitHub profile, opens in a new tab)commented

    This should be part of FieldApi.spec.ts, since they're all related to deleting / delay mounting fields.

    @@ -0,0 +14,21 @@
    14+ const errors: Record<string, string> = {}
    15+ if (!value.existingField) {
    16+ errors.existingField = 'Existing field is required'
    17+ }
    18+ if (!value.delayedField) {
    19+ errors.delayedField = 'Delayed field is required'
    20+ }
    21+ return { fields: errors }
    22+ },
    23+ },
    24+ })
    25+
    26+ form.mount()
    27+
    28+ const existingField = new FieldApi({
    29+ form,
    30+ name: 'existingField',
    31+ })
    32+ existingField.mount()
    33+
    34+ await new Promise((resolve) => setTimeout(resolve, 100))
    LeCarbonator(GitHub profile, opens in a new tab)commented

    There is a sleep helper from utils.ts you can use, along with vi.useFakeTimers(). See other async unit tests for details.

    jiji-hoon96(GitHub profile, opens in a new tab)commented

    Great catch! I've replaced all setTimeout promises with the sleep helper from utils.ts and added vi.useFakeTimers() / vi.useRealTimers() to the async tests, following the pattern used in other test files.

    LeCarbonator(GitHub profile, opens in a new tab)commented

    Same as above, this deals with FieldApi, so it should be part of FieldApi.spec.ts

  • LeCarbonator(GitHub profile, opens in a new tab) approved these changes

    Looks good! Thanks for addressing the changes.

    There's some changeset stuff that has to be adjusted before this is part of a release, but I see no urgent changes in this PR. Sorry for the delay!

  • Sign in to join this conversation.