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
Composable API
The following sections documents each available property on the useField
composable.
name: string | Ref<string> | () => string
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.
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.
setValue: Ref<TValue = unknown>
A method to update the fields value.
jsconst { setValue } = useField('field', value => !!value);
setValue('hello world') // sets the value and validates the field
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, 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 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.
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) |