# Validation Outputs

The values that a form works with might not be the values you need to send to the backend. For example, an optional description might be an empty string in the form, but it needs to be stored as `null`. We need to transform an empty description to `null` before submission.

## Transform in `onSubmit`

For simple transformations, `onSubmit` is more than enough. Adjust the value just before sending it.

```ts fixture=reactHook
const form = useForm({
  defaultValues: { description: '' },
  onSubmit: async ({ value }) => {
    const textOrNull = value.description === '' ? null : value.description

    await saveProfile({ description: textOrNull })
  },
})
```

## Reuse a schema's output

If you're using a Standard Schema library like [Zod](https://zod.dev/) or [Valibot](https://valibot.dev/), the schema
may have already transformed the value for the backend. However, `onSubmit`'s `value` property always contains
the form's values without schema transformations.

To reuse the schema's transformed value in `onSubmit`, read it from `validatorOutputs`. This array has one entry for each form-level validator, in the same order as the `validators` array. A schema validator's entry contains its output, including any transformations.

In the examples below, the schema is the first and only validator, so `schemaResult` contains its output:

<!-- ::start:tabs variant="files" -->

```ts title="Zod" fixture=reactWithHelpers
import { useForm } from '@tanstack/react-form'
import { z } from 'zod'

const optionalText = z.string().transform((str) => (str === '' ? null : str))

const schema = z.object({
  description: optionalText,
})

function ProfileForm() {
  const form = useForm({
    defaultValues: { description: '' },
    validators: [
      {
        run: schema,
      },
    ],
    onSubmit: async ({ validatorOutputs }) => {
      const [schemaResult] = validatorOutputs

      await saveProfile(schemaResult)
    },
  })
}
```

```ts title="Valibot" fixture=reactWithHelpers
import { useForm } from '@tanstack/react-form'
import * as v from 'valibot'

const optionalText = v.pipe(
  v.string(),
  v.transform((str) => (str === '' ? null : str)),
)

const schema = v.object({
  description: optionalText,
})

function ProfileForm() {
  const form = useForm({
    defaultValues: { description: '' },
    validators: [
      {
        run: schema,
      },
    ],
    onSubmit: async ({ validatorOutputs }) => {
      const [schemaResult] = validatorOutputs

      await saveProfile(schemaResult)
    },
  })
}
```

```ts title="Arktype" fixture=reactWithHelpers
import { useForm } from '@tanstack/react-form'
import { type } from 'arktype'

const optionalText = type('string').pipe((str) => (str === '' ? null : str))

const schema = type({
  description: optionalText,
})

function ProfileForm() {
  const form = useForm({
    defaultValues: { description: '' },
    validators: [
      {
        run: schema,
      },
    ],
    onSubmit: async ({ validatorOutputs }) => {
      const [schemaResult] = validatorOutputs

      await saveProfile(schemaResult)
    },
  })
}
```

```ts title="Effect" fixture=reactWithHelpers
import { useForm } from '@tanstack/react-form'
import { Schema } from 'effect'

const optionalText = Schema.transform(
  Schema.String,
  Schema.NullOr(Schema.String),
  {
    strict: true,
    decode: (str) => (str === '' ? null : str),
    encode: (str) => str ?? '',
  },
)

const struct = Schema.Struct({
  description: optionalText,
})

const schema = Schema.standardSchemaV1(struct)

function ProfileForm() {
  const form = useForm({
    defaultValues: { description: '' },
    validators: [
      {
        run: schema,
      },
    ],
    onSubmit: async ({ validatorOutputs }) => {
      const [schemaResult] = validatorOutputs

      await saveProfile(schemaResult)
    },
  })
}
```

<!-- ::end:tabs -->

## Reuse a validator function's output

You may have to transform the form's values before validating them. To avoid parsing the values twice, you can return any data from a validator
by wrapping it in `createOutput`. Output data does not count as a validation error.

To access the output data, `onSubmit` receives `validatorOutputs`, an array with one entry for each form-level validator, in the same order as the `validators` array.

```ts fixture=reactHook
const form = useForm({
  defaultValues: { description: '' },
  validators: [
    {
      run: ({ value }) => {
        if (value.description.length > 200) {
          return 'Description is too long!'
        }

        return undefined
      },
    },
    {
      run: ({ value, createOutput }) => {
        const description = value.description === '' ? null : value.description

        // ... do validation

        return createOutput({ description })
      },
    },
  ],
  onSubmit: async ({ validatorOutputs }) => {
    const [nothing, output] = validatorOutputs

    await saveProfile(output)
  },
})
```

## Reusing data across validators

Currently, while `onSubmit` can reuse data from validators, you cannot reuse data between validators. For example, suppose the
schema and the validator function both need to parse the description first. The recommended way to avoid parsing it twice is to merge the two
validators:

<!-- ::start:tabs variant="files" -->

```ts title="Zod" fixture=reactWithHelpers
import { useForm } from '@tanstack/react-form'
import { z } from 'zod'

const optionalText = z.string().transform((str) => (str === '' ? null : str))

const schema = z.object({
  description: optionalText,
})

function ProfileForm() {
  const form = useForm({
    defaultValues: { description: '' },
    validators: [
      {
        run: ({ value, parseIssues, createOutput }) => {
          const result = schema.safeParse(value)

          if (!result.success) return parseIssues(result.error.issues)

          // validate with result.data
          return createOutput(result.data)
        },
      },
    ],
    onSubmit: async ({ validatorOutputs }) => {
      const [schemaResult] = validatorOutputs

      await saveProfile(schemaResult)
    },
  })
}
```

```ts title="Valibot" fixture=reactWithHelpers
import { useForm } from '@tanstack/react-form'
import * as v from 'valibot'

const optionalText = v.pipe(
  v.string(),
  v.transform((str) => (str === '' ? null : str)),
)

const schema = v.object({
  description: optionalText,
})

function ProfileForm() {
  const form = useForm({
    defaultValues: { description: '' },
    validators: [
      {
        run: ({ value, parseIssues, createOutput }) => {
          const result = v.safeParse(schema, value)

          if (!result.success) return parseIssues(result.issues)

          // validate with result.output
          return createOutput(result.output)
        },
      },
    ],
    onSubmit: async ({ validatorOutputs }) => {
      const [schemaResult] = validatorOutputs

      await saveProfile(schemaResult)
    },
  })
}
```

```ts title="Arktype" fixture=reactWithHelpers
import { useForm } from '@tanstack/react-form'
import { type } from 'arktype'

const optionalText = type('string').pipe((str) => (str === '' ? null : str))

const schema = type({
  description: optionalText,
})

function ProfileForm() {
  const form = useForm({
    defaultValues: { description: '' },
    validators: [
      {
        run: ({ value, parseIssues, createOutput }) => {
          const result = schema(value)

          if (result instanceof type.errors) return parseIssues(result)

          // validate with result
          return createOutput(result)
        },
      },
    ],
    onSubmit: async ({ validatorOutputs }) => {
      const [schemaResult] = validatorOutputs

      await saveProfile(schemaResult)
    },
  })
}
```

```ts title="Effect" fixture=reactWithHelpers
import { useForm } from '@tanstack/react-form'
import { Either, ParseResult, Schema } from 'effect'

const optionalText = Schema.transform(
  Schema.String,
  Schema.NullOr(Schema.String),
  {
    strict: true,
    decode: (str) => (str === '' ? null : str),
    encode: (str) => str ?? '',
  },
)

const schema = Schema.Struct({
  description: optionalText,
})

function ProfileForm() {
  const form = useForm({
    defaultValues: { description: '' },
    validators: [
      {
        run: ({ value, parseIssues, createOutput }) => {
          const result = Schema.decodeUnknownEither(schema)(value)

          if (Either.isLeft(result)) {
            return parseIssues(
              ParseResult.ArrayFormatter.formatErrorSync(result.left),
            )
          }

          // validate with result.right
          return createOutput(result.right)
        },
      },
    ],
    onSubmit: async ({ validatorOutputs }) => {
      const [schemaResult] = validatorOutputs

      await saveProfile(schemaResult)
    },
  })
}
```

<!-- ::end:tabs -->

> [!NOTE] Schemas and validator functions
> For the curious, here's roughly what happens behind the scenes when you pass a schema to `run`:
>
> ```ts
> import { useForm, type StandardSchemaV1 } from '@tanstack/react-form'
>
> // Compatible libraries implement this interface.
> declare const schema: StandardSchemaV1<{ description: string }>
>
> useForm({
>   defaultValues: { description: '' },
>   validators: [
>     { run: schema },
>     {
>       // The same behavior using a function:
>       run: async ({ value, parseIssues, createOutput }) => {
>         const result = await schema['~standard'].validate(value)
>
>         if (result.issues) return parseIssues(result.issues)
>
>         return createOutput(result.value)
>       },
>     },
>   ],
> })
> ```
