Skip to content
Source
Sign inSign up
TanStack/form

Validation onSubmit does not re-trigger with conditionally rendered fields #1874

Send to my agent
Open413n(GitHub profile, opens in a new tab) opened this issue 3 comments

Describe the bug

The onSubmit validator is not re-triggering after first time when a "dynamic" field has changed. In this case I'm using Zod's discriminated union to decide whether to show this or that field, but this bug happens also when using for example a superRefine to conditionally validate a field. The first submit triggers correctly the onSubmit validator, but then if we change the field and show the other input field and submit again, it does not work trigger the validator. Even with canSubmitWhenInvalid: true.

There is a similar issue #1780 that points to this error but it's not actually the same. In that issue the author resolved the issue just putting canSubmitWhenInvalid: true, but actually the problem we have found is in the validation not getting triggered.

Your minimal, reproducible example

https://stackblitz.com/edit/tanstack-form-q2pndiqf?file=src%2Findex.tsx

Steps to reproduce

  1. Click on Submit -> Should show the error for thisField
  2. Change the Select to the value That
  3. Click again on Submit -> Should show the error for thatField, but it does not.

If we change the validators to run on onChange, it works! It works also if after submitting you change an input or on blur.

Expected behavior

I would expect that the onSubmit validator would run on submitting the form and it would have the same result of the onChange schema validation

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS: MacOS
  • Browser: Chrome
  • Version: 142.0.7444.60

TanStack Form adapter

react-form

TanStack Form version

1.25.0

TypeScript version

5.9.3

Additional context

No response

  1. 413n(GitHub profile, opens in a new tab) changed the title

  2. Same problem, if anyone can share a workaround in the meantime. I'm struggling revalidating somehow the only field when change happen. But it seems to triggers validation for the whole form

  3. Hey @413n @Teyik0 ,

    Let me offer some insights.

    Validation upon submission is like a two-stage pipeline: Stage 1 is field-level validation, and Stage 2 is form-level validation. Since field-level validators weren't specified, Stage 1 completes with this state:

    FieldthisOrThatthisFieldthatField
    isFieldValidtruetruetrue

    So, the pipeline progresses to Stage 2. The 'thisField' fails form-level validation (your onSubmit zod schema). Now you have the following:

    FieldthisOrThatthisFieldthatField
    isFieldValidtruefalsetrue

    The pipeline exits and the error message for 'thisField' is displayed.

    Now you've changed the value of 'thisOrThat' to 'that' and pressed the 'Submit' button. Here's the new starting point for the validation pipeline:

    FieldthisOrThatthisFieldthatField
    isFieldValidtruefalsetrue

    Not all fields are valid, so the pipeline fails field-level validation and exits at Stage 1. The form-level validator doesn't execute, and therefore 'thatField' remains valid and has no error message to display.

    Note: Even though 'thisField' isn't displayed, its state persists. One workaround is to clear the error state of the hidden field. Here's one way to do that:

    <form.AppField
      name="thisOrThat"
      listeners={{
        onChange: ({ value }) => {
          // Clear submit errors for the now-irrelevant field
          if (value === 'that') {
            form.setFieldMeta('thisField', (prev) => ({
              ...prev,
              errorMap: { ...prev.errorMap, onSubmit: undefined },
              errorSourceMap: { ...prev.errorSourceMap, onSubmit: undefined },
            }))
          } else {
            form.setFieldMeta('thatField', (prev) => ({
              ...prev,
              errorMap: { ...prev.errorMap, onSubmit: undefined },
              errorSourceMap: { ...prev.errorSourceMap, onSubmit: undefined },
            }))
          }
        },
      }}
    >
      {(field) => (
        <select
          value={field.state.value}
          onChange={(e) => field.handleChange(e.target.value as 'this' | 'that')}
        >
          <option value="this">This</option>
          <option value="that">That</option>
        </select>
      )}
    </form.AppField>

    I hope this helps.

  4. @HM-23-HM Thanks you for the given workaround.

    Give the sample for people working on double nested structure. Needed to adapt somehow. Very far from being good but still.

    <form.AppField
    	mode="array"
    	name={`attributes.create[${index}].values`}
    	listeners={{
    		onChange: ({ value, fieldApi }) => {
    			// When values change, clear error state for removed indices
    			const currentLength = value?.length ?? 0;
    			const allFieldKeys = Object.keys(
    				form.state.fieldMeta,
    			);
    
    			// Find and clear metadata for indices that no longer exist
    			for (const key of allFieldKeys) {
    				const match = key.match(
    					new RegExp(
    						`attributes\\.create\\[${index}\\]\\.values\\[(\\d+)\\]`,
    					),
    				);
    				if (match) {
    					const idx = Number(match[1]);
    					if (idx >= currentLength) {
    						// This index no longer exists, clear its metadata
    						fieldApi.form.setFieldMeta(
    							key as any,
    							(prev) => ({
    								...prev,
    								errorMap: {},
    								errors: [],
    							}),
    						);
    					}
    				}
    			}
    		},
    	}}
    >
    	{(avField) => (
    		<avField.Content className="col-span-4">
    			<avField.MultiSelect
    				creatable
    				maxCount={5}
    				onCreateNew={async (value) => {
    					avField.pushValue(value);
    					return {
    						label: value.toLowerCase(),
    						value: value.toLowerCase(),
    					};
    				}}
    				options={
    					avField.state.value?.map(
    						(v) =>
    							({
    								label: v,
    								value: v,
    							}) as MultiSelectOption,
    					) ?? null
    				}
    				placeholder="Select or create attribute values"
    			/>
    			{avField.state.value?.map((v, j) => (
    				<form.AppField
    					key={v}
    					name={`attributes.create[${index}].values[${j}]`}
    				>
    					{(valueField) => <valueField.Message />}
    				</form.AppField>
    			))}
    			<avField.Message />
    		</avField.Content>
    	)}
    </form.AppField>
  5. LeCarbonator(GitHub profile, opens in a new tab) added labelsv2: needs investigation

Sign in to join this conversation.