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.

tsconst { 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

TypeScript Definition

The full signature of the useField function looks like this:

tsinterface FieldOptions<TValue = unknown> {
  validateOnValueUpdate?: boolean;   // if the field should be validated when the value changes (default is true)
  initialValue?: MaybeRef<TValue>;
  validateOnMount?: boolean; ; // if the field should be validated when the component is mounted
  bails?: boolean; // if the field validation should run all validations
  label?: MaybeRef<string | undefined>; // A friendly name to be used in `generateMessage` config instead of the field name, has no effect with yup rules
  standalone?: boolean; //  // Excludes the field from participating in any `Form` or `useForm` contexts, useful for creating inputs that do contribute to the `values`, In other words, the form won't pick up or validate fields marked as standalone
  type?: string;  // can be either `checkbox` or `radio` or `file` any other types doesn't have an effect.

  // Both of these are only used if `type="checkbox"`. They are ignored otherwise
  checkedValue?: MaybeRef<TValue>; // If a checkbox this will be used as the new field value when it is checked.
  uncheckedValue?: MaybeRef<TValue>; // If a single checkbox this will be used as the field value when it is unchecked.

  keepValueOnUnmount?: boolean; // if the form value should be kept when the field is unmounted, default is `false`
  modelPropName?: string; // the model prop name, default is `modelValue`
  syncVModel?: boolean; // If the model prop should be synced with value changes for `v-model` support, default is `true`
}

interface ValidationResult {
  errors: string[];
  valid: boolean;
}

interface FieldState<TValue = unknown> {
  value: TValue;
  dirty: boolean;
  touched: boolean;
  errors: string[];
}

export interface FieldMeta<TValue> {
  touched: boolean; // field was blurred or attempted submit
  dirty: boolean; // field value was changed
  valid: boolean; // field passed all validations
  validated: boolean; // field was validated via user input
  pending: boolean; // field is pending validation
  initialValue: TValue | undefined; // initial field value
}

/**
 * validated-only: only mutate the previously validated fields
 * silent: do not mutate any field
 * force: validate all fields and mutate their state
 */
export type SchemaValidationMode = 'validated-only' | 'silent' | 'force';

export interface ValidationOptions {
  mode: SchemaValidationMode;
}

function useField<TValue = unknown>(
  fieldName: MaybeRef<string>,
  rules: RuleExpression,
  opts?: FieldOptions
): {
  name: MaybeRef<string>;  // The field name
  value: Ref<TValue>; // the field's current value
  meta: FieldMeta<TValue>;
  errors: Ref<string[]>; // all error messages
  errorMessage: Ref<string | undefined>; // the first error message
  label?: MaybeRef<string | undefined>;
  type?: string;
  bails?: boolean;
  checkedValue?: MaybeRef<TValue>;
  uncheckedValue?: MaybeRef<TValue>;
  checked?: Ref<boolean>; // Present if input type is checkbox
  resetField(state?: Partial<FieldState<TValue>>): void; // resets errors and field meta, updates the current value to its initial value
  handleReset(): void;
  validate(opts?: Partial<ValidationOptions>): Promise<ValidationResult>; // validates and updates the errors and field meta
  handleChange(e: Event | unknown, shouldValidate?: boolean): void;  // updates the value and triggers validation
  handleBlur(e?: Event): void; // updates the field meta associated with blur event
  setState(state: Partial<FieldState<TValue>>): void;
  setTouched(isTouched: boolean): void;
  setErrors(message: string | string[]): void;
  setValue(value: TValue): void;
};

Composable API

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

name: string

The field name, this is a static string and cannot be changed.

value: Ref<TValue = unknown>

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

jsconst { 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.

meta: FieldMeta<TValue = unknown>

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

tsinterface 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
}

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.

usage

jsconst { meta } = useField('field', value => !!value);

meta; // { valid: true, invalid: false, dirty: true, .... }

errors: Ref<string[]>

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

jsconst { errors } = useField('field', value => !!value);

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

errorMessage: ComputedRef<string | undefined>

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

jsconst { errorMessage } = useField('field', value => !!value);

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

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

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.

jsconst { 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<!-- ⛔️ Unsafe -->
<button @click="resetField">Reset</button>

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

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

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

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

jsconst { setErrors } = useField('field', value => !!value);

// Sets a 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([]);

handleReset: () => void

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.

jsconst { handleReset } = useField('field', value => !!value);

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

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

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).

jsconst { validate } = useField('field', value => !!value);

// trigger validation
await validate();

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

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>

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

Sets the touched meta flag to true

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

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

setTouched: (isTouched: boolean) => void

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

jsconst { setTouched } = useField('field', value => !!value);

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

checked: ComputedRef<boolean> | undefined

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.

jsconst { 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.