Skip to main content

FieldApi

The FieldApi class provides methods to interact with individual form fields, including getting and setting values, managing metadata, and performing validation.

Constructor

new FieldApi<TParentData, TName, TData>(options: FieldApiOptions<TParentData, TName, TData>)
Creates a new FieldApi instance.
options
FieldApiOptions
required
Configuration options for the field. See FieldOptions for details.
FieldApi
FieldApi
A new FieldApi instance

Example

import { FormApi, FieldApi } from '@tanstack/form-core'

const form = new FormApi({ defaultValues: { firstName: '' } })

const field = new FieldApi({
  form,
  name: 'firstName',
  validators: {
    onChange: ({ value }) => {
      if (value.length < 2) {
        return 'First name must be at least 2 characters'
      }
      return undefined
    },
  },
})

Properties

form

form: FormApi<TParentData>
A reference to the parent form API instance.

name

name: TName
The field name (supports dot notation for nested fields).

options

options: FieldApiOptions<TParentData, TName, TData>
The current options for the field.

state

get state(): FieldState<TParentData, TName, TData>
The current state of the field, including value and metadata.

Methods

mount()

Mounts the field instance to the form. Returns a cleanup function.
mount(): () => void
cleanup
() => void
A function to call when unmounting the field

Example

const cleanup = field.mount()

// Later, when unmounting
cleanup()

update()

Updates the field instance with new options.
update(opts: FieldApiOptions): void
opts
FieldApiOptions
required
New options to apply to the field

getValue()

Deprecated: Use field.state.value instead.
Gets the current field value.
getValue(): TData
value
TData
The current value of the field

setValue()

Sets the field value and runs the change validator.
setValue(
  updater: Updater<TData>,
  options?: UpdateMetaOptions
): void
updater
Updater<TData>
required
A value or function that returns the new value
options.dontUpdateMeta
boolean
default:false
If true, does not update field metadata
options.dontValidate
boolean
default:false
If true, does not trigger validation
options.dontRunListeners
boolean
default:false
If true, does not run field listeners

Example

// Set a value directly
field.setValue('John')

// Set a value using an updater function
field.setValue((prev) => prev.toUpperCase())

// Set a value without validation
field.setValue('John', { dontValidate: true })

getMeta()

Gets the field metadata.
getMeta(): FieldMeta
meta
FieldMeta
The field metadata including errors, touched state, validation status, etc.

Example

const meta = field.getMeta()
console.log('Is touched:', meta.isTouched)
console.log('Is valid:', meta.isValid)
console.log('Errors:', meta.errors)

setMeta()

Sets the field metadata.
setMeta(updater: Updater<FieldMetaBase>): void
updater
Updater<FieldMetaBase>
required
A value or function that returns the new metadata

Example

// Mark field as touched
field.setMeta((prev) => ({ ...prev, isTouched: true }))

// Clear errors
field.setMeta((prev) => ({ ...prev, errorMap: {} }))

getInfo()

Gets the field information object.
getInfo(): FieldInfo<TParentData>
info
FieldInfo
The field information object containing the field instance and validation metadata

validate()

Validates the field value.
validate(
  cause: ValidationCause,
  opts?: { skipFormValidation?: boolean }
): ValidationError[] | Promise<ValidationError[]>
cause
'change' | 'blur' | 'submit' | 'mount'
required
The cause of the validation
opts.skipFormValidation
boolean
default:false
If true, skips form-level validation for this field
errors
ValidationError[] | Promise<ValidationError[]>
Array of validation errors (if any)

Example

const errors = await field.validate('change')
if (errors.length > 0) {
  console.log('Validation failed:', errors)
}

handleChange()

Handles the change event for the field.
handleChange(updater: Updater<TData>): void
updater
Updater<TData>
required
A value or function that returns the new value

Example

// In a React component
<input
  value={field.state.value}
  onChange={(e) => field.handleChange(e.target.value)}
/>

handleBlur()

Handles the blur event for the field.
handleBlur(): void

Example

<input
  value={field.state.value}
  onChange={(e) => field.handleChange(e.target.value)}
  onBlur={field.handleBlur}
/>

Array Field Methods

The FieldApi provides methods for working with array values:

pushValue()

Pushes a new value to the array field.
pushValue(
  value: TData[number],
  options?: UpdateMetaOptions
): void
value
TData[number]
required
The value to push
options
UpdateMetaOptions
Options to control metadata updates, validation, and listeners

insertValue()

Inserts a value at the specified index.
insertValue(
  index: number,
  value: TData[number],
  options?: UpdateMetaOptions
): void
index
number
required
The index to insert at
value
TData[number]
required
The value to insert

replaceValue()

Replaces a value at the specified index.
replaceValue(
  index: number,
  value: TData[number],
  options?: UpdateMetaOptions
): void
index
number
required
The index to replace
value
TData[number]
required
The new value

removeValue()

Removes a value at the specified index.
removeValue(
  index: number,
  options?: UpdateMetaOptions
): void
index
number
required
The index to remove

swapValues()

Swaps the values at two indices.
swapValues(
  aIndex: number,
  bIndex: number,
  options?: UpdateMetaOptions
): void
aIndex
number
required
The first index
bIndex
number
required
The second index

moveValue()

Moves a value from one index to another.
moveValue(
  aIndex: number,
  bIndex: number,
  options?: UpdateMetaOptions
): void
aIndex
number
required
The source index
bIndex
number
required
The destination index

clearValues()

Clears all values from the array.
clearValues(options?: UpdateMetaOptions): void

Example: Working with Array Fields

const todosField = new FieldApi({
  form,
  name: 'todos',
  defaultValue: [],
})

// Add a new todo
todosField.pushValue({ text: 'Buy milk', completed: false })

// Insert at position 0
todosField.insertValue(0, { text: 'First task', completed: false })

// Remove the second item
todosField.removeValue(1)

// Swap first and second items
todosField.swapValues(0, 1)

// Clear all todos
todosField.clearValues()

setErrorMap()

Updates the field’s error map.
setErrorMap(errorMap: ValidationErrorMap): void
errorMap
ValidationErrorMap
required
The new error map to set

Example

field.setErrorMap({
  onChange: 'This field is required',
  onBlur: undefined,
})

parseValueWithSchema()

Parses the field’s value with a given schema and returns issues (if any). This method does NOT set any internal errors.
parseValueWithSchema(
  schema: StandardSchemaV1<TData>
): StandardSchemaV1Issue[] | undefined
schema
StandardSchemaV1<TData>
required
The standard schema to parse this field’s value with
issues
StandardSchemaV1Issue[] | undefined
Array of schema validation issues (if any)

parseValueWithSchemaAsync()

Async version of parseValueWithSchema.
parseValueWithSchemaAsync(
  schema: StandardSchemaV1<TData>
): Promise<StandardSchemaV1Issue[] | undefined>
schema
StandardSchemaV1<TData>
required
The standard schema to parse this field’s value with
issues
Promise<StandardSchemaV1Issue[] | undefined>
Promise resolving to array of schema validation issues (if any)

Type Parameters

TParentData
any
required
The TypeScript type of the parent form data
TName
DeepKeys<TParentData>
required
The field name type (supports dot notation)
TData
DeepValue<TParentData, TName>
required
The TypeScript type of the field value
TOnMount
FieldValidateOrFn
Type of the onMount validator
TOnChange
FieldValidateOrFn
Type of the onChange validator
TOnChangeAsync
FieldAsyncValidateOrFn
Type of the onChangeAsync validator
TOnBlur
FieldValidateOrFn
Type of the onBlur validator
TOnBlurAsync
FieldAsyncValidateOrFn
Type of the onBlurAsync validator
TOnSubmit
FieldValidateOrFn
Type of the onSubmit validator
TOnSubmitAsync
FieldAsyncValidateOrFn
Type of the onSubmitAsync validator

See Also

Build docs developers (and LLMs) love