Skip to content
Source
Sign inSign up
TanStack/form

fix(form-core): clear previous invalid sync validation errors on FormApi #1157

Mergedjuanvilladev(GitHub profile, opens in a new tab)merged 7 commits intomain fromrefs/pull/1157/headmerged by crutchcorn(GitHub profile, opens in a new tab)

Fixes: https://github.com/TanStack/form/issues/999

When performing sync validation, ensure that previous field errors are cleared if they are no longer present in the new validation result. This prevents stale validation errors from persisting in the form state.

To achieve this I have added a new prevFieldsErrorMap:

  /**
   * @private fields previously validated via form level validations
   */
  prevFieldsErrorMap: FieldsErrorMapFromValidator<TFormData> = {}

This allows us to keep track of field level errors that were added at the form level. We then use this map to clear them out if no new errors appear for the same field.

        for (const field of Object.keys(this.prevFieldsErrorMap) as Array<
          DeepKeys<TFormData>
        >) {
          const fieldMeta = this.getFieldMeta(field)
          if (
            fieldMeta?.errorMap[errorMapKey] &&
            !newFieldsErrorMap[field]?.[errorMapKey]
          ) {
            this.setFieldMeta(field, (prev) => ({
              ...prev,
              errorMap: {
                ...prev.errorMap,
                [errorMapKey]: undefined,
              },
            }))
          }
        }

All tests are passing. The tricky part was keeping track of what field errors were added from the form level. Added a test covering this specific scenario within FormApi.spec.ts

    1. harry-whorlow(GitHub profile, opens in a new tab)commented

      So you'll see under this comment this warning:

      Screenshot 2025-02-19 at 22 15 44

      I'm going to go out on a limb and guess, that because I've contributed before, my account has been approved for workflows. So I presume until a maintainer is available for review that the workflows will not run until approved.

      But you can check it will pass before by running the test:ci script which consists of:

      • pnpm sherif
      • pnpm test:knip
      • pnpm test:eslint
      • pnpm test:lib
      • pnpm test:types
      • pnpm test:build
      • pnpm build

      If in the future you want to figure it out for yourself, you can head into the .github/workflows/ci.yml and seeing what test scrip they call, in this case test:ci.

      Screenshot 2025-02-19 at 22 31 27

      Then head to the package.json and calling that script, or the individual parts.

      Screenshot 2025-02-19 at 22 30 44
    2. Thanks! @harry-whorlow that makes sense. Cool, I just ran test:ci and got a successful pass: NX Successfully ran targets test:sherif, test:knip, test:eslint, test:lib, test:types, test:build, build for 39 projects (1m)

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

      View your CI Pipeline Execution ↗ for commit f230dcd8c88d56801cb4513a8630a0e4fa060002.

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded1m 59sView ↗
      nx run-many --target=build --exclude=examples/**✅ Succeeded23sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-02-25 07:10:55 UTC

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

      Codecov Report

      All modified and coverable lines are covered by tests :white_check_mark:

      Project coverage is 88.50%. Comparing base (25b7543) to head (f230dcd). Report is 2 commits behind head on main.

      Additional details and impacted files
      @@            Coverage Diff             @@
      ##             main    #1157      +/-   ##
      ==========================================
      + Coverage   88.42%   88.50%   +0.07%     
      ==========================================
        Files          27       27              
        Lines        1210     1218       +8     
        Branches      320      322       +2     
      ==========================================
      + Hits         1070     1078       +8     
        Misses        125      125              
        Partials       15       15              

      :umbrella: View full report in Codecov by Sentry. :loudspeaker: Have feedback on the report? Share it here.

    6. harry-whorlow(GitHub profile, opens in a new tab)commented

      Just be aware that now the ci is running, it'll add a commit to your branch.

      This commit will contain generated docs and type definitions. So git pull before you push again, as your remote will be one commit ahead from your local.

      Good luck with the pr 🫡

    7. juanvilladev(GitHub profile, opens in a new tab)commented

      Another approach I thought of was to update the errorMap type to store the validation source. This would allow us to know which errors should be clearable at the form level once stale. This would be quite a breaking change though so unsure...

      Something like changing the current type below to:

      export type ValidationErrorMap = {
        [K in ValidationErrorMapKeys]?: ValidationError
      }
      export type ValidationErrorMap = {
        [K in ValidationErrorMapKeys]?: { error: ValidationError, source: ValidationSource }
      }

      We already have a type for Validation Source here.

      Since @crutchcorn is already reworking the ValidationErrors maybe something like this could be considered, else I'm not sure how else to know which errors on the map came from the form and should be cleared.

      My current approach works because we create essentially a form sourced error map for each field within prevFieldsErrorMap

    8. juanvilladev(GitHub profile, opens in a new tab)commented

      Resolved conflicts and updated type for prevFieldsErrorMap to uptake new types:

        /**
         * @private map of errors originated from form level validators
         */
        prevFieldsErrorMap: FormErrorMapFromValidator<
          TFormData,
          TOnMount,
          TOnChange,
          TOnChangeAsync,
          TOnBlur,
          TOnBlurAsync,
          TOnSubmit,
          TOnSubmitAsync
        > = {}

      Moved existing code for clearing errorMap on for submit when user edits field up into the same batch call.

    9. Balastrong(GitHub profile, opens in a new tab) approved these changes

    10. Hey @Balastrong, just checking in—let me know if there's anything else I need to do for this PR to be merged, or if it's just a matter of waiting. Appreciate your time!

Sign in to join this conversation.