diff --git a/.changeset/six-baboons-fix.md b/.changeset/six-baboons-fix.md new file mode 100644 index 0000000000..9ee40c1140 --- /dev/null +++ b/.changeset/six-baboons-fix.md @@ -0,0 +1,5 @@ +--- +'@tanstack/form-core': minor +--- + +Allow form validators to omit field schema issues from form errors. diff --git a/docs/framework/react/guides/validation.md b/docs/framework/react/guides/validation.md index f4b7ac4d75..d8d115dec1 100644 --- a/docs/framework/react/guides/validation.md +++ b/docs/framework/react/guides/validation.md @@ -164,6 +164,25 @@ validator index in `schemaOutputs` during submit (for example, `schemaOutputs[0]`); `value` remains the form's raw editable state rather than the parsed output. +By default, a form-level Standard Schema validator also includes every schema +issue in `form.state.errors`, including issues routed to fields. To show only +issues without a field path in form errors, set +`includeFieldIssuesInFormErrors: false` on that validator: + +```tsx +validators: [ + { + triggers: ['change'], + run: accountSchema, + includeFieldIssuesInFormErrors: false, + }, +] +``` + +Field-path issues still appear in `field.errors` and keep the form invalid. +The same setting applies when that form validator returns schema issues through +`parseIssues`. + For custom schema routing, call a schema's safe parse API inside `run` and pass its issues to the provided `parseIssues` helper. diff --git a/packages/form-core/src/ssr.lib.ts b/packages/form-core/src/ssr.lib.ts index d401a8852d..01df6e09e1 100644 --- a/packages/form-core/src/ssr.lib.ts +++ b/packages/form-core/src/ssr.lib.ts @@ -2,6 +2,7 @@ import { batch } from '@tanstack/store' import { defaultInternalBaseFieldMeta } from './FieldApi/fieldState.lib' import { visitAllFormFields } from './FieldApi/fieldTraversal.lib' import { parseStandardSchemaIssues } from './standardSchema.lib' +import { shouldIncludeFieldIssuesInFormErrors } from './validation/execution.lib' import { evaluate } from './utils.lib' import { runValidatorPipeline } from './validation' import { createErrorMap } from './validation.public' @@ -149,14 +150,19 @@ export async function validateServerValues< formApi: undefined, }, hasFailedBefore: false, - getContext: (ctx) => ({ + getContext: (ctx, validator) => ({ event: 'server', signal: ctx.signal, formApi: undefined, value: values, createErrorMap, parseIssues: (issues) => - parseStandardSchemaIssues(issues, values, 'form'), + parseStandardSchemaIssues( + issues, + values, + 'form', + shouldIncludeFieldIssuesInFormErrors(validator), + ), }), scope: 'form', }) diff --git a/packages/form-core/src/standardSchema.lib.ts b/packages/form-core/src/standardSchema.lib.ts index e57bb2dc1d..c6c3bb0949 100644 --- a/packages/form-core/src/standardSchema.lib.ts +++ b/packages/form-core/src/standardSchema.lib.ts @@ -77,6 +77,7 @@ export function parseStandardSchema( schema: StandardSchemaV1, value: any, scope: 'form' | 'field', + includeFieldIssuesInFormErrors = true, ): Promise<{ result: FormValidateResult schemaResult: TOutput | null @@ -95,6 +96,7 @@ export function parseStandardSchema( result.issues, value, scope, + includeFieldIssuesInFormErrors, ) return { @@ -109,6 +111,7 @@ export function parseStandardSchemaIssues( issues: ReadonlyArray, value: TValue, scope: 'form', + includeFieldIssuesInFormErrors?: boolean, ): ParsedStandardSchemaIssues export function parseStandardSchemaIssues( issues: ReadonlyArray, @@ -119,18 +122,22 @@ export function parseStandardSchemaIssues( issues: ReadonlyArray, value: TValue, scope: 'form' | 'field', + includeFieldIssuesInFormErrors?: boolean, ): ParsedStandardSchemaIssues | Array export function parseStandardSchemaIssues( issues: ReadonlyArray, value: TValue, scope: 'form' | 'field', + includeFieldIssuesInFormErrors = true, ): ParsedStandardSchemaIssues | Array { if (scope === 'field') { return issues.slice() } return { - form: issues.slice(), + form: includeFieldIssuesInFormErrors + ? issues.slice() + : issues.filter((issue) => getPathFromIssue(issue, value) === ''), fields: prefixSchemaToErrors( issues, value, diff --git a/packages/form-core/src/validation.public.ts b/packages/form-core/src/validation.public.ts index 9145fc9373..906d4caca7 100644 --- a/packages/form-core/src/validation.public.ts +++ b/packages/form-core/src/validation.public.ts @@ -458,6 +458,13 @@ export type ServerFormValidatorFn = ValidatorFn< export interface FormValidator extends BaseValidator< FormValidatorFn | StandardSchemaV1 > { + /** + * Whether field-path Standard Schema issues also appear in form errors. + * Field errors are still routed to their fields when this is `false`. + * + * @default true + */ + includeFieldIssuesInFormErrors?: boolean runOnSubmit?: boolean | ValidationPredicateFn runOnMount?: boolean triggerDebounceMs?: diff --git a/packages/form-core/src/validation/execution.lib.ts b/packages/form-core/src/validation/execution.lib.ts index 150d0c4aeb..3c40767aea 100644 --- a/packages/form-core/src/validation/execution.lib.ts +++ b/packages/form-core/src/validation/execution.lib.ts @@ -65,6 +65,15 @@ type AnyPipelineValidator = | FormGroupValidator | FieldValidator | Validator + +export function shouldIncludeFieldIssuesInFormErrors( + validator: AnyPipelineValidator, +): boolean { + return !( + 'includeFieldIssuesInFormErrors' in validator && + validator.includeFieldIssuesInFormErrors === false + ) +} export type AnyValidatorContext = | FormValidatorContext | ServerFormValidatorContext @@ -252,7 +261,12 @@ export async function executeValidator( scope: 'field' | 'form', ): Promise> { if (isStandardSchema(validator.run)) { - return parseStandardSchema(validator.run, context.value, scope) as never + return parseStandardSchema( + validator.run, + context.value, + scope, + shouldIncludeFieldIssuesInFormErrors(validator), + ) as never } return { diff --git a/packages/form-core/src/validation/mount.lib.ts b/packages/form-core/src/validation/mount.lib.ts index 419e555e9b..0a49342e1e 100644 --- a/packages/form-core/src/validation/mount.lib.ts +++ b/packages/form-core/src/validation/mount.lib.ts @@ -6,7 +6,11 @@ import { } from '../standardSchema.lib' import { isPromiseLike } from '../utils.lib' import { isErrorResult } from './errors.lib' -import { createValidatorAbortContext, parseFieldIssues } from './execution.lib' +import { + createValidatorAbortContext, + parseFieldIssues, + shouldIncludeFieldIssuesInFormErrors, +} from './execution.lib' import type { AnyInternalValidatorInstance } from '../ValidatorInstance.lib' import type { InternalFormApi } from '../FormApi/FormApi.lib' import type { AnyInternalFieldApi } from '../FieldApi/FieldApi.lib' @@ -38,7 +42,10 @@ export interface FormMountValidatorPipelineResult { interface MountValidatorPipelineArgs { pipeline: ReadonlyArray - getContext: (signal: AbortSignal) => AnyValidatorContext + getContext: ( + signal: AbortSignal, + validatorInstance: AnyInternalValidatorInstance, + ) => AnyValidatorContext scope: 'field' | 'form' onResult?: (result: PipelineResult) => void } @@ -97,11 +104,16 @@ function executeMountValidator( cancelDebouncer: true, }) - const context = getContext(signal) + const context = getContext(signal, validatorInstance) try { if (isStandardSchema(validator.run)) { - return parseStandardSchema(validator.run, context.value, scope) + return parseStandardSchema( + validator.run, + context.value, + scope, + shouldIncludeFieldIssuesInFormErrors(validator), + ) .then((result) => { if (signal.aborted) { return createEmptyMountValidationResult() @@ -293,14 +305,19 @@ export function runFormMountValidatorPipeline({ }: FormMountValidatorPipelineArgs): FormMountValidatorPipelineResult { return runMountValidatorPipeline>({ pipeline, - getContext: (signal) => ({ + getContext: (signal, validatorInstance) => ({ event: 'mount' as never, signal, formApi, value: formApi.state.values, createErrorMap, parseIssues: (issues) => - parseStandardSchemaIssues(issues, formApi.state.values, 'form'), + parseStandardSchemaIssues( + issues, + formApi.state.values, + 'form', + shouldIncludeFieldIssuesInFormErrors(validatorInstance.definition), + ), }), scope: 'form', onResult, diff --git a/packages/form-core/src/validation/pipeline.lib.ts b/packages/form-core/src/validation/pipeline.lib.ts index 9ba77b800b..be71f17a39 100644 --- a/packages/form-core/src/validation/pipeline.lib.ts +++ b/packages/form-core/src/validation/pipeline.lib.ts @@ -10,6 +10,7 @@ import { isServerValidateContext, parseFieldIssues, runMaybeDebouncedValidator, + shouldIncludeFieldIssuesInFormErrors, shouldRunValidator, } from './execution.lib' import type { AnyInternalValidatorInstance } from '../ValidatorInstance.lib' @@ -46,7 +47,10 @@ interface ValidatorPipelineArgs { context: InputContext pipeline: ReadonlyArray hasFailedBefore: boolean - getContext: (inputContext: ValidateContext) => AnyValidatorContext + getContext: ( + inputContext: ValidateContext, + validator: AnyInternalValidatorInstance['definition'], + ) => AnyValidatorContext scope: 'field' | 'form' validatorInstancesToRun?: ReadonlySet | null onResult?: (result: PipelineResult) => void @@ -197,7 +201,11 @@ export async function runValidatorPipeline({ validatorInstance, context, onExecute: (ctx) => { - return executeValidator(validator, getContext(ctx), scope) + return executeValidator( + validator, + getContext(ctx, validator), + scope, + ) }, }).then< PendingPipelineResult< @@ -252,7 +260,7 @@ export function runFormValidatorPipeline({ context, onResult, hasFailedBefore, - getContext: (ctx) => { + getContext: (ctx, validator) => { if (isServerValidateContext(ctx)) { throw new Error('Server validation cannot run through client pipeline') } @@ -266,7 +274,12 @@ export function runFormValidatorPipeline({ parseIssues: ( issues: Parameters[0], ) => - parseStandardSchemaIssues(issues, ctx.formApi.state.values, 'form'), + parseStandardSchemaIssues( + issues, + ctx.formApi.state.values, + 'form', + shouldIncludeFieldIssuesInFormErrors(validator), + ), } if (!isFieldValidateContext(ctx)) { diff --git a/packages/form-core/tests/FormApi/validation.spec.ts b/packages/form-core/tests/FormApi/validation.spec.ts index 2ca600b9a8..e98db8ac92 100644 --- a/packages/form-core/tests/FormApi/validation.spec.ts +++ b/packages/form-core/tests/FormApi/validation.spec.ts @@ -147,6 +147,119 @@ describe('form - validation', () => { ]) }) + it('keeps field schema issues out of form errors when configured', async () => { + const rootIssue = { message: 'Invalid form' } + const fieldIssue = { message: 'Name is required', path: ['name'] } + const schema: StandardSchemaV1<{ name: string }> = { + '~standard': { + version: 1, + vendor: 'test', + validate: () => ({ issues: [rootIssue, fieldIssue] }), + }, + } + const form = new InternalFormApi({ + defaultValues: { name: '' }, + validators: [ + { + run: schema, + triggers: ['change'], + includeFieldIssuesInFormErrors: false, + }, + ], + }) + const field = form._getOrCreateFieldApi({ name: 'name' }) + + await form.validate('change') + + expect(form.state.errors).toEqual([rootIssue]) + expect(field.errors).toEqual([fieldIssue]) + }) + + it('applies schema issue reporting separately to each form validator', async () => { + const form = new InternalFormApi({ + defaultValues: { name: '' }, + validators: [ + { + run: z.object({ name: z.string().min(1, 'First error') }), + triggers: ['change'], + includeFieldIssuesInFormErrors: false, + }, + { + run: z.object({ name: z.string().min(1, 'Second error') }), + triggers: ['change'], + }, + ], + }) + const field = form._getOrCreateFieldApi({ name: 'name' }) + + await form.validate('change') + + expect(form.state.errors).toEqual([ + expect.objectContaining({ message: 'Second error' }), + ]) + expect(field.errors).toEqual([ + expect.objectContaining({ message: 'First error' }), + expect.objectContaining({ message: 'Second error' }), + ]) + }) + + it('keeps field-only schema issues on the field and clears them after valid input', async () => { + const fieldIssue = { message: 'Name is required', path: ['name'] } + const schema: StandardSchemaV1<{ name: string }> = { + '~standard': { + version: 1, + vendor: 'test', + validate: (value) => { + const data = value as { name: string } + return data.name ? { value: data } : { issues: [fieldIssue] } + }, + }, + } + const form = new InternalFormApi({ + defaultValues: { name: '' }, + validators: [ + { + run: schema, + triggers: ['change'], + includeFieldIssuesInFormErrors: false, + }, + ], + }) + const field = form._getOrCreateFieldApi({ name: 'name' }) + + await form.validate('change') + expect(form.state.errors).toEqual([]) + expect(field.errors).toEqual([fieldIssue]) + expect(form.state.isValid).toBe(false) + + field.handleChange('Ada', { causeValidation: false }) + await form.validate('change') + expect(form.state.errors).toEqual([]) + expect(field.errors).toEqual([]) + expect(form.state.isValid).toBe(true) + }) + + it('applies the schema issue setting to parseIssues in a form validator', async () => { + const rootIssue = { message: 'Invalid form' } + const fieldIssue = { message: 'Name is required', path: ['name'] } + const form = new InternalFormApi({ + defaultValues: { name: '' }, + validators: [ + { + run: ({ parseIssues }) => parseIssues([rootIssue, fieldIssue]), + triggers: ['change'], + includeFieldIssuesInFormErrors: false, + }, + ], + }) + const field = form._getOrCreateFieldApi({ name: 'name' }) + + await form.validate('change') + + expect(form.state.errors).toEqual([rootIssue]) + expect(field.errors).toEqual([fieldIssue]) + }) + it('handles validators returning error arrays', async () => { const form = new InternalFormApi({ defaultValues: { name: '' }, @@ -657,6 +770,33 @@ describe('form - validation', () => { }) }) + it('applies the schema issue setting during mount validation', async () => { + const fieldIssue = { message: 'Name is required', path: ['name'] } + const schema: StandardSchemaV1<{ name: string }> = { + '~standard': { + version: 1, + vendor: 'test', + validate: () => ({ issues: [fieldIssue] }), + }, + } + const form = new InternalFormApi({ + defaultValues: { name: '' }, + validators: [ + { + run: schema, + runOnMount: true, + triggers: [], + includeFieldIssuesInFormErrors: false, + }, + ], + }) + + await vi.waitFor(() => { + expect(form.state.errors).toEqual([]) + expect(form._tryGetFieldApi('name')?.errors).toEqual([fieldIssue]) + }) + }) + it('tracks isValidating while an asynchronous mount validator is pending', async () => { vi.useFakeTimers() const form = new InternalFormApi({ diff --git a/packages/form-core/tests/serverValidate.spec.ts b/packages/form-core/tests/serverValidate.spec.ts index b2c6fa92bb..d4f41459a3 100644 --- a/packages/form-core/tests/serverValidate.spec.ts +++ b/packages/form-core/tests/serverValidate.spec.ts @@ -297,6 +297,36 @@ describe('server validation', () => { }) }) + it('keeps field schema issues out of server form errors when configured', async () => { + const rootIssue = { message: 'Invalid form' } + const fieldIssue = { message: 'Name is required', path: ['name'] } + const schema = { + '~standard': { + version: 1 as const, + vendor: 'test', + validate: () => ({ issues: [rootIssue, fieldIssue] }), + }, + } + const options = formOptions({ + defaultValues: { name: '' }, + validators: [ + { + run: schema, + triggers: ['server'], + includeFieldIssuesInFormErrors: false, + }, + ], + }) + + const { serverState } = expectServerValidateFailure( + await validateServerValues(options, { name: '' }), + ) + expect(serverState.validationResults[0]?.result).toEqual({ + form: [rootIssue], + fields: { name: [fieldIssue] }, + }) + }) + it('hydrates posted values and server errors into form state', async () => { const options = formOptions({ defaultValues: { name: '', age: 0 }, diff --git a/packages/form-core/tests/standardSchema.spec.ts b/packages/form-core/tests/standardSchema.spec.ts index 745d363c25..79f0c2116b 100644 --- a/packages/form-core/tests/standardSchema.spec.ts +++ b/packages/form-core/tests/standardSchema.spec.ts @@ -196,6 +196,27 @@ describe('standard schema validation', () => { }) }) + it('keeps only pathless issues at form level when configured', async () => { + const issues = [ + { message: 'Invalid form' }, + { message: 'Empty path', path: [] }, + { message: 'Empty segment', path: [''] }, + { message: 'Name is required', path: ['user', 'name'] }, + ] satisfies Array + const schema = getSchema(() => Promise.resolve({ issues })) + + await expect( + parseStandardSchema(schema, { user: { name: '' } }, 'form', false), + ).resolves.toEqual({ + result: { + form: issues.slice(0, 3), + fields: { 'user.name': [issues[3]] }, + }, + schemaResult: null, + hasSchemaResult: false, + }) + }) + it('calls validate with the provided value', async () => { const validate = vi.fn((value: unknown) => ({ value })) const schema = getSchema(validate)