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.
Configuration options for the field. See FieldOptions for details.
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: FormApi<TParentData>
A reference to the parent form API instance.
name
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.
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
New options to apply to the field
getValue()
Deprecated: Use field.state.value instead.
Gets the current field value.
The current value of the field
setValue()
Sets the field value and runs the change validator.
setValue(
updater: Updater<TData>,
options?: UpdateMetaOptions
): void
A value or function that returns the new value
If true, does not update field metadata
If true, does not trigger validation
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 })
Gets the field metadata.
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)
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>
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
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
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.
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
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
replaceValue()
Replaces a value at the specified index.
replaceValue(
index: number,
value: TData[number],
options?: UpdateMetaOptions
): void
removeValue()
Removes a value at the specified index.
removeValue(
index: number,
options?: UpdateMetaOptions
): void
swapValues()
Swaps the values at two indices.
swapValues(
aIndex: number,
bIndex: number,
options?: UpdateMetaOptions
): void
moveValue()
Moves a value from one index to another.
moveValue(
aIndex: number,
bIndex: number,
options?: UpdateMetaOptions
): void
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
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
Type of the onMount validator
Type of the onChange validator
Type of the onChangeAsync validator
Type of the onBlur validator
Type of the onBlurAsync validator
Type of the onSubmit validator
Type of the onSubmitAsync validator
See Also