---
layout: ../../layouts/PageLayout.astro
title: useField
description: API reference for the useField composition API function
menuTitle: useField()
order: 5
---

import DocTip from '@/components/DocTip.vue';
import CodeTitle from '@/components/CodeTitle.vue';

# useField

`useField` is a custom composition API function that allows you to create data models that's automatically validated that you can then use to build your own custom input components with validation capabilities. It is very useful if you plan to build a UI component library that needs to have validation capabilities. In other words it acts as a primitive to allow you to compose validation logic into your components.

The most basic usage looks like this:

```vue
<template>
  <div>
    <input v-model="value" />
    <span>{{ errorMessage }}</span>
  </div>
</template>

<script setup>
import { useField } from 'vee-validate';

// a simple `name` field with basic required validator
const { value, errorMessage } = useField('name', inputValue => !!inputValue);
</script>
```

Whenever the `value` ref is updated it will be validated and the `errorMessage` ref will be automatically filled with the first error message. Usually you would bind the `value` ref to your inputs using `v-model` or any other means and whenever you want to validate your field you update the `value` binding with the new value.

Additionally you can use `yup` as a validator:

```vue
<script setup>
import { useField } from 'vee-validate';
import * as yup from 'yup';

const { value, errorMessage } = useField('email', yup.string().email().required());
</script>
```

You are responsible for when the field validates, blurs or when its value changes. This gives you greater control over the `Field` component which may include or implement sensible defaults for most common use cases.

## Usage with TypeScript

You can use `useField` with typescript and type the field's value type to ensure safety when manipulating it's value. The `useField` function is a generic function that receives the value type and applies it on the various interactions you have with its API.

```ts
const { value, resetField } = useField<string>('email', yup.string().email());

value.value = 1; // ⛔️  Error
value.value = 'test@example.com'; // ✅

resetField({
  value: 1, // ⛔️  Error
});
resetField({
  value: 'test@example.com', // ✅
});
```

The validation rules can be either a string, object, function or a yup schema:

```js
// Globally defined rules with `defineRule`, Laravel-like syntax
useField('password', 'required|min:8');

// Globally defined rules object
useField('password', { required: true, min: 8 });

// Simple validation function
useField('password', value => {
  if (!value) {
    return 'password is required';
  }

  if (value.length < 8) {
    return 'password must be at least 8 characters long';
  }

  return true;
});

// Yup validation
useField('password', yup.string().required().min(8));
```

## API Reference

### Composable API

The following sections documents each available property on the `useField` composable.

<CodeTitle level="4">

`name: string | Ref<string> | () => string`

</CodeTitle>

The field name, it can be a string or a reactive ref to a string or a getter than returns a string. It is used to identify the field and specify its value path.

<CodeTitle level="4">

`value: Ref<TValue = unknown>`

</CodeTitle>

A reactive reference to the field's current value, can be changed and will trigger validation by default unless disabled by the `validateOnValueUpdate` option.

```js
const { value } = useField('field', value => !!value);

value.value = 'hello world'; // sets the value and validates the field
```

You can also bind it with `v-model` to get two-way value binding with validation.

<CodeTitle level="4">

`setValue: Ref<TValue = unknown>`

</CodeTitle>

A method to update the fields value.

```js
const { setValue } = useField('field', value => !!value);

setValue('hello world') // sets the value and validates the field
```

<CodeTitle level="4">

`meta: FieldMeta<TValue = unknown>`

</CodeTitle>

Contains useful information/flags about the field status, should be treated as **read only**.

```ts
interface FieldMeta {
  touched: boolean; // if the field has been blurred (via handleBlur)
  dirty: boolean; // if the field has been manipulated (via handleChange)
  valid: boolean; // if the field doesn't have any errors
  pending: boolean; // if validation is in progress
  initialValue?: any; // the field's initial value
}
```

<DocTip title="The valid flag">

The `valid` flag on the meta object can be tricky, because by default it stars off with `true` for a few moments, only then it is updated to its proper state.

Combining your `valid` flag checks with `dirty` will yield the expected result based on user interaction.

</DocTip>

**usage**

```js
const { meta } = useField('field', value => !!value);

meta; // { valid: true, dirty: true, .... }
```

<CodeTitle level="4">

`errors: Ref<string[]>`

</CodeTitle>

A reactive reference containing all error messages for the field, should be treated as **read only**

```js
const { errors } = useField('field', value => !!value);

errors.value; // ['field is not valid']
```

<CodeTitle level="4">

`errorMessage: ComputedRef<string | undefined>`

</CodeTitle>

A computed reference that returns the first error in the `errors` array, a handy shortcut to display error messages

```js
const { errorMessage } = useField('field', value => !!value);

errorMessage.value; // 'field is not valid' or undefined
```

<CodeTitle level="4">

`resetField: (state?: Partial<FieldState>) => void`

</CodeTitle>

Resets the field's validation state, by default it reverts all `meta` object to their default values and clears out the error messages. It also updates the field value to its initial value without validating them.

```js
const { resetField } = useField('field', value => !!value);

// reset the field meta and its initial value and clears errors
resetField();

// reset the meta state, clears errors and updates the field value and its initial value
resetField({
  value: 'new value',
});

// resets the meta state, resets the field to its initial value and sets the errors
resetField({
  errors: ['bad field'],
});

// Marks the field as touched, while resetting its value and errors.
resetField({
  touched: true,
});

// Changes the meta, initial and current values and sets the errors for the field
resetField({
  value: 'new value',
  touched: true,
  errors: ['bad field'],
});
```

Note that it is unsafe to use this function as an event handler directly, check the following snippet:

```vue-html
<!-- ⛔️ Unsafe -->
<button @click="resetField">Reset</button>

<!-- ✅  Safe -->
<button @click="resetField()">Reset</button>
```

You can also use `handleReset` which is a safe alternative for `resetField`.

<CodeTitle level="4">

`setErrors: (errors: string | string[]) => void`

</CodeTitle>

Sets then field errors, you can pass a single message string or an array of errors.

```js
const { setErrors } = useField('field', value => !!value);

// Sets the errors to a single error message
setErrors('field is required');

// sets the errors to multiple error messages
setErrors(['field is required', 'field must be valid']);

// clears the errors
setErrors([]);
```

<CodeTitle level="4">

`handleReset: () => void`

</CodeTitle>

Similar to `resetField` but it doesn't accept any arguments and can be safely used as an event handler. The values won't be validated after reset.

```js
const { handleReset } = useField('field', value => !!value);

// reset the field validation state and its initial value
handleReset();
```

<CodeTitle level="4">

`validate: () => Promise<{ errors: string[] }>`

</CodeTitle>

Validates the field's current value and returns a promise that resolves with an object containing the error messages emitted by the various rule(s).

```js
const { validate } = useField('field', value => !!value);

// trigger validation
await validate();
```

<CodeTitle level="4">

`handleChange: (evt: Event | any) => void`

</CodeTitle>

Updates the field value, and validates the field. Can be used as an event handler to bind on the field. If the passed argument isn't an event object it will be used as the new value for that field.

It sets the `dirty` meta flag to `true`

```vue
<template>
  <input @change="handleChange" type="text" />
</template>

<script setup>
const { handleChange } = useField('field');

handleChange('new value'); // update field value and validate it
handleChange('new value 2', false); // update field value without validating it (you have to turn off validateOnValueUpdate)
</script>
```

<CodeTitle level="4">

`handleBlur: (evt: Event | any) => void`

</CodeTitle>

Sets the `touched` meta flag to `true`

```vue
<template>
  <input @blur="handleBlur" type="text" />
</template>

<script setup>
const { handleBlur } = useField('field');
</script>
```

<CodeTitle level="4">

`setTouched: (isTouched: boolean) => void`

</CodeTitle>

Sets the `touched` meta flag for this field, useful to create your own `blur` handlers

```js
const { setTouched } = useField('field', value => !!value);

// mark the field as touched
setTouched(true);
```

<CodeTitle level="4">

`checked: ComputedRef<boolean> | undefined`

</CodeTitle>

A computed property that indicates if the field should be checked or unchecked, only available if `type=checkbox` or `type=radio` in field options. Useful if you are creating [custom checkboxes](/examples/custom-checkboxes).

```js
const { checked } = useField('field', ..., {
  type: 'checkbox',
  valueProp: 'Checkbox value'
});

checked.value; // true or false
```

For more information on how you might use the `checked` property, check the [custom checkboxes example](/examples/custom-checkboxes).

## Additional options

To pass additional configuration to your fields you can use more options.

```vue
<template>
  <div>
    <input v-model="value" />
    <span>{{ errorMessage }}</span>
  </div>
</template>

<script setup>
import { useField } from 'vee-validate';

// a simple `company` field with some options passed into it
const { value, errorMessage } = useField('company', ..., {
  label: 'Your company',
  initialValue: ''
});
</script>
```

| Field options                          |
| -------------------------------------- |
| `type`                                 |
| `label`                                |
| `initialValue`                         |
| `validateOnMount`                      |
| `bails `                               |
| `standalone`                           |
| `validateOnValueUpdate`                |
| `keepValueOnUnmount`                   |
| `syncVModel`                           |
| `checkedValue` (checkbox/radio only)   |
| `uncheckedValue` (checkbox/radio only) |
