Skip to content

Programmatic validation breaks form state #5034

Description

@hotcholocate

Prerequisites

What theme are you using?

core

Version

6.4.2

Current Behavior

List of errors contains stale entries

Expected Behavior

List of errors contains correct entries for the formData and schema provided

Steps To Reproduce

  1. Trigger programmatic validation in an effect.
  2. Attempt to update form props.

Environment

Anything else?

Example 0

import Form from '@rjsf/core'
import type { RJSFSchema } from '@rjsf/utils'
import validator from '@rjsf/validator-ajv8'
import { useCallback, useEffect, useRef, useState } from 'react'

const schemaA: RJSFSchema = { type: 'string', minLength: 10 }

const schemaB: RJSFSchema = { type: 'string', minLength: 20 }

const Example0 = () => {
  const [schema, setSchema] = useState(schemaA)

  const handleClick = useCallback(() => {
    setSchema((prev) => (prev === schemaA ? schemaB : schemaA))
  }, [])

  const ref = useRef<Form>(null)

  // https://rjsf-team.github.io/react-jsonschema-form/docs/usage/validation/#validate-form-programmatically
  useEffect(() => {
    // breaks form state
    ref.current?.validateForm()

    // a hack
    // const timeout = setTimeout(() => ref.current?.validateForm(), 0)
    // return () => clearTimeout(timeout)
  }, [schema])

  return (
    <>
      <Form formData="formData" ref={ref} schema={schema} validator={validator} />
      <button onClick={handleClick}>Toggle Schema</button>
      <p>
        Schema: <output>{JSON.stringify(schema)}</output>
      </p>
    </>
  )
}


Example 0 demo:

Screen.Recording.2026-04-16.at.13.35.30.mov

Example 1

import Form from '@rjsf/core'
import type { RJSFSchema } from '@rjsf/utils'
import validator from '@rjsf/validator-ajv8'
import { useCallback, useEffect, useRef, useState } from 'react'

const schema: RJSFSchema = { type: 'string', maxLength: 11, minLength: 8 }

const valueA = 'invalid'

const valueB = 'also invalid'

const Example1 = () => {
  const [formData, setFormData] = useState(valueA)

  const handleClick = useCallback(() => {
    setFormData((prev) => (prev === valueA ? valueB : valueA))
  }, [])

  const ref = useRef<Form>(null)

  // https://rjsf-team.github.io/react-jsonschema-form/docs/usage/validation/#validate-form-programmatically
  useEffect(() => {
    // breaks form state
    ref.current?.validateForm()

    // a hack
    // const timeout = setTimeout(() => ref.current?.validateForm(), 0)
    // return () => clearTimeout(timeout)
  }, [])

  return (
    <>
      <Form formData={formData} ref={ref} schema={schema} validator={validator} />
      <button onClick={handleClick}>Toggle Data</button>
      <p>
        Data: <output>{JSON.stringify(formData)}</output>
      </p>
    </>
  )
}

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions