Vue Forms 03 ๐ Introduction to VeeValidate โ Installing VeeValidate, Understanding Form State, and Composition API vs Components
VeeValidate is the form library that most Vue 3 projects reach for, and version 4 is a complete rewrite built on the Composition API. It replaces the older directive and provider components of version 3 with a small set of composables โ useForm, useField, defineField, useFieldArray, useFormContext โ and then wraps those same composables in a thin component layer, <Form>, <Field>, <ErrorMessage>. The two layers are not two libraries; they are two doors into one engine.
The engine holds three pieces of state for every form: values, the current data; errors, the message per field; and meta, the flags describing the form’s lifecycle โ has it been touched, has it changed, is it valid, is it still checking. Everything the library exposes is a view over those three objects. Once you understand their shape and who owns them, every other API in VeeValidate becomes a variation on a theme you already know.
This chapter is the entry point to the series. It covers installation and the optional packages that supply rules, messages, and schema adapters; the three-part state model and the subtle reactivity rules around it; and the decision between the composable API and the component API, with the criteria that actually separate them in practice. Later chapters build on the state model introduced here.
Key point: VeeValidate is a state machine wrapped around your form data, not a validator. The validator is pluggable, the schema source is pluggable, and the rendering layer is pluggable โ but values, errors, and meta are the fixed contract that every API surface exposes, identically.
Why VeeValidate Exists
The scattered-state problem. A hand-written form in Vue starts innocently: one ref for the email, one for the password, one for the confirmation. Then each input needs an error ref, a dirty flag, a touched flag, and a rule function. A registration form with eight fields becomes twenty-four refs and eight nearly identical validateEmail() functions. The code does not fail suddenly; it rots by accretion. VeeValidate collapses all of that into one form object with named sub-objects, so adding a field is adding a key, not adding three refs and a handler.
The rule-reuse problem. When validation is written inline inside a component, the required check cannot leave that component. The next form writes it again, slightly differently, with a different error message. VeeValidate’s rules are plain functions with a fixed signature โ value in, true or message out โ so they can be defined once, registered globally with defineRule, and referenced by name from any field in the app. That single signature is what makes the library composable with everything else.
The consistency problem. When validation is wired by hand, “when does it run?” becomes an accident of which event listener someone remembered. One field validates on input, another on blur, a third only on submit. Users experience that inconsistency as bugginess. VeeValidate makes the trigger set explicit and configurable per form and per field โ validateOnInput, validateOnChange, validateOnBlur, validateOnModelUpdate, validateOnMount โ and defaults are uniform across the app.
The cross-field problem. A password confirmation rule needs two values at once. So does a “start date must be before end date” rule, or a “total must equal sum of line items” rule. In hand-written validation, cross-field rules need closures over other refs, which is exactly where the code becomes tangled. VeeValidate passes a validation context as the third argument to every rule, and ctx.form contains every current value in the form. Cross-field validation becomes a normal function that reads one extra object.
The component-library problem. Third-party inputs โ a date picker, a combobox, a masked input โ emit update:modelValue and often nothing else. They do not emit blur in a predictable way, and they do not accept name attributes usefully. VeeValidate accounts for this with defineComponentBinds, which translates a field into a modelValue/onUpdate:modelValue pair that any Vue component understands, and with the v-slot form of <Field> that hands you the raw field props to spread with v-bind.
The trade-off. VeeValidate is a runtime dependency with a learning curve, and it deliberately does not ship a built-in schema language. Yup and Zod support live in separate adapter packages so the core stays small. The cost is that you must choose: global rules registered by name, inline rule functions, or a full schema through toTypedSchema. The benefit is that the same three-part state powers all three approaches, so the choice is reversible.
a. Installing VeeValidate and Choosing a Rule Source
The core package is one install and contains everything needed for the state machine. It is tree-shakeable and has no requirement to register a plugin on the app; you import composables per component.
npm install vee-validate
Version 4 is the Vue 3 line. Version 3 targeted Vue 2 with <ValidationProvider> and <ValidationObserver> components and an extend() global registry, and the two API surfaces are not interchangeable. If a tutorial shows extend("required", ...) at the top of the file, it is a version 3 tutorial and the code will not run against this install.
// src/main.js โ nothing is registered globally for the core package
import { createApp } from "vue";
import App from "./App.vue";
// VeeValidate composables are imported where they are used, so the
// app bootstrap stays untouched. There is no app.use(VeeValidate).
createApp(App).mount("#app");
The four optional packages each solve one problem. @vee-validate/rules ships ready-made rule implementations; @vee-validate/i18n ships translated message dictionaries; @vee-validate/yup and @vee-validate/zod convert a schema object into something VeeValidate can consume.
npm install @vee-validate/rules # required, email, min, max, between, regex, ...
npm install @vee-validate/i18n # localized message templates
npm install @vee-validate/yup # toTypedSchema() for Yup schemas
npm install @vee-validate/zod # toTypedSchema() for Zod schemas
Registering the built-in rules is deliberately manual. Nothing is global until you say so, which keeps unused rules out of the bundle. defineRule takes a name and a function, and the name is what the string rule syntax references.
// src/validation/setup.js
import { defineRule, configure } from "vee-validate";
import { required, email, min } from "@vee-validate/rules";
import { localize, setLocale } from "@vee-validate/i18n";
import en from "@vee-validate/i18n/dist/locale/en.json";
// Each built-in rule is a plain function: (value, params) => true | string
defineRule("required", required);
defineRule("email", email);
defineRule("min", min);
// localize() builds the message generator; setLocale() activates a dictionary
configure({ generateMessage: localize({ en }) });
setLocale("en");
A field then names rules with a pipe-separated string. Parameters follow a colon, so min:8 passes { min: 8 } as the rule’s second argument. Rules run left to right and the first failure short-circuits the rest, which is why required is always written first โ running an email regex against an empty string produces a misleading message.
<Field name="password" type="password" rules="required|min:8" />
<Field name="age" type="number" rules="required|between:18,120" />
Rules can also be passed as functions rather than registered by name. This is the right choice for a rule used in exactly one place, because it avoids polluting the global registry with a name nobody else will reference.
// A local rule: return true to pass, or a string to fail with that message
const evenNumber = (value) => Number(value) % 2 === 0 || "Must be an even number";
// Used as an array; multiple rules are allowed alongside string syntax
// :rules="[evenNumber]"
b. Form State โ values, errors, and meta
Every form is created by useForm, which returns the three state objects plus the functions that mutate them. The return value is large, and it is worth memorizing which bucket each member belongs to.
// src/components/RegisterForm.vue โ <script setup>
import { useForm } from "vee-validate";
const {
values, // reactive record of every current field value
errors, // reactive record of field name -> message (or undefined)
meta, // reactive record of form lifecycle flags
defineField, // turns a field name into [modelRef, attrsToBind]
handleSubmit, // wraps your submit handler with validation
handleReset, // clears values back to their initial state
resetForm, // resets values, errors, and touched in one call
setFieldError, // inject a message for one field (server errors)
setErrors, // inject many messages at once
isSubmitting, // true while handleSubmit's promise is outstanding
} = useForm({
initialValues: { email: "", password: "", confirm: "" },
validateOnMount: false, // do not validate the empty form on first render
});
values is a reactive object keyed by field name. Reading it is the common case: a character counter, a live preview, a conditional block that appears once a field is non-empty. It is not a ref, so destructuring const { email } = values copies a string and breaks reactivity โ the correct pattern is to keep the values reference and read values.email in the template.
// values is reactive, so template expressions re-evaluate on change
const marketingOptIn = computed(() => values.password.length > 0);
// Prefill from an API without marking the form dirty:
// resetForm({ values }) rewrites BOTH the current and the initial values
function loadUser(user) {
resetForm({ values: { email: user.email, password: "", confirm: "" } });
}
Writing to values directly is possible but not the supported path. setFieldValue and setValues exist so that the field-level bookkeeping โ dirty comparison against initialValue, and re-validation if configured โ stays consistent with the change.
errors is a record from field name to message string. A field that has never failed has errors.email === undefined; there is no “empty string” convention to check against, and a field is valid precisely when its key is undefined.
// Reading errors is a plain property lookup
if (errors.email) {
console.warn("Email problem:", errors.email);
}
// Server-side errors are injected into the same record, so the UI
// treats them exactly like locally computed ones
function onConflict() {
setErrors({
email: "This email is already registered.",
});
}
meta is the form-level lifecycle object, and its four flags answer the four questions every form UI asks. valid is true when errors has no messages. dirty is true once any value differs from its initial value. touched is true once any field has been blurred. pending is true while asynchronous validation is still running. meta.initialValues holds the baseline that dirty compares against.
// Drive the submit button from meta, not from a manual boolean
const canSubmit = computed(() => meta.valid && !meta.pending);
// Warn before leaving a half-filled form
const warnOnLeave = computed(() => meta.dirty && !meta.valid);
Fields have their own meta, and the field-level flags are narrower: valid, dirty, touched, pending, and initialValue. useField returns that object alongside the value, the message, and the handlers, which is the rawest useful level of the library.
import { useField } from "vee-validate";
const {
value: confirm, // a ref, bindable with v-model
errorMessage: confirmError, // a computed ref: the first message or undefined
meta: confirmMeta, // { valid, dirty, touched, pending, initialValue }
handleChange, // updates the value from an event
handleBlur, // marks touched and triggers validation
} = useField("confirm", "required", { initialValue: "" });
defineField is the shorthand for the common case. It returns a two-element tuple: a ref to bind with v-model, and an attributes object containing name and the event handlers VeeValidate needs. v-bind on the input is what connects the field to the form โ without it the value updates but the validation triggers never fire.
// defineField returns [modelRef, attrs]
const [email, emailAttrs] = defineField("email", { validateOnInput: true });
const [password, passwordAttrs] = defineField("password");
<template>
<form @submit="onSubmit">
<input v-model="email" v-bind="emailAttrs" type="email" />
<span v-if="errors.email">{{ errors.email }}</span>
<input v-model="password" v-bind="passwordAttrs" type="password" />
<span v-if="errors.password">{{ errors.password }}</span>
</form>
</template>
The field-level options mirror the form-level ones and override them for that field only. validateOnInput: true on the email field means the message appears as the user types; leaving the password field at the default means it validates on change and blur, which is less noisy for a value the user cannot easily proofread.
c. The Composition API Versus the Components
Both surfaces are built from the same composables. <Field> internally calls useField; <Form> internally creates the form context. The difference is who owns the state: with useForm the refs live in your setup block and you control everything; with <Form> the state lives inside the component’s context and you reach it through slot props or useFormContext.
The component form is compact. Rules are strings on the field, the message has a dedicated component, and the form’s state arrives through the default slot.
<template>
<Form v-slot="{ errors, meta, isSubmitting }" @submit="onSubmit">
<Field name="email" type="email" rules="required|email" />
<ErrorMessage name="email" class="error" />
<Field name="password" type="password" rules="required|min:8" />
<ErrorMessage name="password" class="error" />
<button type="submit" :disabled="!meta.valid || isSubmitting">
{{ isSubmitting ? "Creatingโฆ" : "Create account" }}
</button>
</Form>
</template>
<Field> renders an <input> by default. The as prop switches the element, and native children are passed through, so a <select> works without any extra wiring.
<Field name="plan" as="select" rules="required">
<option value="">Choose a plan</option>
<option value="free">Free</option>
<option value="pro">Pro</option>
</Field>
<Field name="bio" as="textarea" rules="max:280" rows="4" />
For a third-party component, the slot form gives you the raw field object to spread. It contains value, name, onInput, onChange, onBlur, and โ for checkbox and radio types โ checked. Spreading it onto the component is what forwards the events back into VeeValidate.
<Field name="country" v-slot="{ field, errors }">
<MyCombobox v-bind="field" :options="countries" />
<p v-if="errors[0]" class="error">{{ errors[0] }}</p>
</Field>
In the slot, errors is an array of strings rather than a record, which is why the index access errors[0] is used there and property access is used on the form-level errors.
The composable form is more verbose but strictly more capable. Values are ordinary refs you can pass to other composables, watch, serialize, or seed from a store. Prefilling from an API call, conditionally showing a step based on a field’s value, and unit-testing the submit handler are all natural because nothing is hidden inside a component instance.
// The state is yours: it can be watched, passed, or tested
const [email, emailAttrs] = defineField("email");
watch(email, (next) => {
// Suggest a username from the email domain, for example
suggestedUsername.value = next.split("@")[0] ?? "";
});
Deeply nested children can read the ancestor form without prop drilling through useFormContext. It returns the same three state objects, so a small display component can react to values while the parent owns the form.
<!-- src/components/PasswordMeter.vue -->
<script setup>
import { useFormContext } from "vee-validate";
// Same reactive objects the ancestor form created
const { values, meta } = useFormContext();
</script>
<template>
<meter :value="values.password.length" min="0" max="16" />
<small v-if="meta.dirty">Unsaved changes</small>
</template>
The two surfaces mix freely inside one <Form> tree, which is the practical answer to the “which one” question: use components for the layout-heavy simple fields and drop into composables for the one field that needs custom logic.
Complete Example Session
// ============================================
// PART 1: INSTALL AND REGISTER THE RULES
// ============================================
// npm install vee-validate @vee-validate/rules @vee-validate/i18n
// src/validation/setup.js
import { defineRule, configure } from "vee-validate";
import { required, email, min } from "@vee-validate/rules";
import { localize, setLocale } from "@vee-validate/i18n";
import en from "@vee-validate/i18n/dist/locale/en.json";
defineRule("required", required); // empty values fail
defineRule("email", email); // RFC-shaped address check
defineRule("min", min); // length or numeric minimum
configure({ generateMessage: localize({ en }) }); // message templates
setLocale("en"); // activate the dictionary
// ============================================
// PART 2: THE FORM AND ITS THREE BUCKETS
// ============================================
// src/components/RegisterForm.vue
import { useForm } from "vee-validate";
const {
values, // { email, password, confirm }
errors, // { email?, password?, confirm? }
meta, // { valid, dirty, touched, pending }
defineField,
handleSubmit,
resetForm,
setErrors,
isSubmitting,
} = useForm({
initialValues: { email: "", password: "", confirm: "" },
validateOnMount: false, // no red text before the user has typed
});
// ============================================
// PART 3: BINDING FIELDS WITH defineField
// ============================================
// Tuple destructuring: [ref for v-model, attrs for v-bind]
const [email, emailAttrs] = defineField("email", { validateOnInput: true });
const [password, passwordAttrs] = defineField("password");
// ============================================
// PART 4: A FIELD WITH ITS OWN META
// ============================================
import { useField } from "vee-validate";
const {
value: confirm,
errorMessage: confirmError,
meta: confirmMeta, // valid / dirty / touched / pending / initialValue
handleChange,
handleBlur,
} = useField("confirm", "required|password_match", { initialValue: "" });
// ============================================
// PART 5: A CROSS-FIELD RULE
// ============================================
// The third argument is the validation context; ctx.form holds every value
defineRule("password_match", (value, _params, ctx) => {
if (value !== ctx.form.password) {
return "Passwords do not match"; // a string means "failed"
}
return true; // true means "passed"
});
// ============================================
// PART 6: SUBMIT, SERVER ERRORS, AND RESET
// ============================================
const onSubmit = handleSubmit(
async (submittedValues) => {
try {
await api.register(submittedValues); // isSubmitting flips automatically
resetForm(); // values, errors, touched cleared
} catch (err) {
// Push server messages into the same errors record the UI reads
setErrors({ email: "This email is already registered." });
}
},
({ errors: invalid }) => {
// Second callback runs when validation blocked the submit
const first = Object.keys(invalid)[0];
document.querySelector(`[name="${first}"]`)?.focus();
}
);
// ============================================
// PART 7: THE SAME FORM AS COMPONENTS
// ============================================
// <Form v-slot="{ errors, meta }" @submit="onSubmit">
// <Field name="email" type="email" rules="required|email" />
// <ErrorMessage name="email" />
// <Field name="password" type="password" rules="required|min:8" />
// <ErrorMessage name="password" />
// <button :disabled="!meta.valid">Create account</button>
// </Form>
// ============================================
// PART 8: REACHING THE FORM FROM A CHILD
// ============================================
// PasswordMeter.vue โ no props, no emits, no injection boilerplate
import { useFormContext } from "vee-validate";
const { values: sharedValues } = useFormContext();
// sharedValues.password updates live as the parent's field changes
// ============================================
// PART 9: AN ASYNCHRONOUS RULE
// ============================================
defineRule("unique_email", async (value) => {
if (!value) return true; // let `required` own emptiness
const taken = await api.isEmailTaken(value); // network round trip
return taken ? "This email is already registered" : true;
});
// While it awaits, meta.pending is true โ use it for the spinner
// ============================================
// PART 10: PREFILL WITHOUT MARKING THE FORM DIRTY
// ============================================
function loadProfile(user) {
// resetForm({ values }) rewrites current AND initial values,
// so meta.dirty stays false and the form looks untouched
resetForm({
values: { email: user.email, password: "", confirm: "" },
});
}
The ten parts followed one form from install through rule registration, the three state buckets, field binding, field-level meta, a cross-field rule, submission with server errors, the component equivalent, context access from a child, an async rule, and a clean prefill.
Quick Reference
Packages
| Package | Provides |
|---|---|
vee-validate | Core composables and components |
@vee-validate/rules | Ready-made rule functions |
@vee-validate/i18n | localize, setLocale, message dictionaries |
@vee-validate/yup | toTypedSchema for Yup |
@vee-validate/zod | toTypedSchema for Zod |
The Three State Objects
| Object | Shape | Purpose |
|---|---|---|
values | { [field]: any } | Current data, keyed by name |
errors | { [field]: string } | First failing message per field |
meta | object | valid, dirty, touched, pending |
Composables
| Composable | Returns |
|---|---|
useForm | State, defineField, handleSubmit, resetForm |
useField | value, errorMessage, meta, handlers |
defineField | [modelRef, attrs] tuple |
useFormContext | Ancestor form state |
useFieldArray | Dynamic list helpers |
Components
| Component | Role |
|---|---|
<Form> | Provides context, slot exposes state |
<Field> | Renders input, accepts rules |
<ErrorMessage> | Renders the message for one field |
<FieldArray> | Renders repeated field groups |
Rule Contract
| Return | Meaning |
|---|---|
true | Field passes |
"message" | Field fails with that message |
Promise<true | string> | Async; sets meta.pending |
Best Practices
โ Do This:
// Read values through the object, never destructure it
const total = computed(() => values.price * values.qty); // โ
// Bind the attrs from defineField so triggers are wired
<input v-model="email" v-bind="emailAttrs" /> // โ
// Put required first in the pipe, before format rules
<Field name="email" rules="required|email" /> // โ
// Drive the button from meta, not from a manual flag
<button :disabled="!meta.valid || meta.pending">Save</button> // โ
// Inject server errors into the same errors record
setErrors({ email: "Already registered" }); // โ
// Prefill as initial values so dirty stays honest
resetForm({ values: fetched }); // โ
// Keep async rules off the input event
defineField("email", { validateOnInput: false }); // โ
โ Don’t Do This:
// Destructuring breaks reactivity on a reactive object
const { email } = values; // โ
// Forgetting v-bind leaves validation triggers unwired
<input v-model="email" /> // โ
// Format rules before required produce misleading messages
<Field name="email" rules="email|required" /> // โ
// A manual boolean drifts out of sync with real state
const isValid = ref(true); // โ
// Writing to errors directly bypasses the field bookkeeping
errors.email = "nope"; // โ
// Mutating values instead of the field API
values.email = "a@b.co"; // โ
// Running an API-backed rule on every keystroke
defineField("email", { validateOnInput: true }); // with async โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Validation never fires | attrs from defineField not bound | Spread v-bind="attrs" |
| Message disappears on re-render | Recomputed from local state | Read errors[name] |
| Form is dirty on load | Values assigned after useForm | resetForm({ values }) |
| Wrong message shown | email rule runs before required | Reorder the pipe string |
| Cross-field rule always passes | Rule reads the wrong field name | Use ctx.form[name] |
| Async rule floods the API | validateOnInput left on | Set it false on that field |
| Server error never clears | Only setErrors was called | Reset the field after success |
| Version 3 code copied | extend() and ValidationProvider | Rewrite for v4 composables |
Real-World Examples
1. Global rule registration
import { defineRule } from "vee-validate";
import { required, email } from "@vee-validate/rules";
defineRule("required", required);
defineRule("email", email);
2. Local rule in one component
const even = (v) => Number(v) % 2 === 0 || "Must be even";
// template: :rules="[even]"
3. Rule with parameters
<Field name="age" type="number" rules="required|between:18,120" />
4. Field-level meta for inline hints
const { meta: m } = useField("email", "required|email");
// m.touched && !m.valid โ show the message
5. Async uniqueness check
defineRule("unique", async (v) =>
(await api.taken(v)) ? "Already registered" : true
);
6. Cross-field comparison
defineRule("after_start", (v, _p, ctx) =>
v > ctx.form.start ? true : "Must be after start"
);
7. Third-party component binding
<Field name="when" v-slot="{ field }">
<DatePicker v-bind="field" />
</Field>
8. Schema validation instead of rules
import { toTypedSchema } from "@vee-validate/zod";
useForm({ validationSchema: toTypedSchema(schema) });
9. Reset after a successful save
await api.save(values);
resetForm(); // values, errors, touched all cleared
10. Accessing the form from a nested component
import { useFormContext } from "vee-validate";
const { values } = useFormContext();
Visual
The Three Buckets
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ONE FORM, THREE REACTIVE BUCKETS โ
โ โ
โ values errors meta โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ
โ โ email โ โ email โ โ valid โ โ
โ โ password โ โ password โ โ dirty โ โ
โ โ confirm โ โ confirm โ โ touched โ โ
โ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โ pending โ โ
โ โโโโโโโโโโโโโโโโ โ
โ bound to inputs rendered as text gates the button โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Two Surfaces, One Engine
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ COMPOSITION API COMPONENT API โ
โ useForm() <Form> โ
โ useField() <Field> โ
โ defineField() <ErrorMessage> โ
โ useFieldArray() <FieldArray> โ
โ useFormContext() <FormContext> โ
โ โ โ โ
โ โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ values / errors / meta โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Validation Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ FIELD EVENT โ
โ โ โ
โ โผ โ
โ validateOnInput? โโnoโโโบ value updates, no check yet โ
โ โyes โ
โ โผ โ
โ rules run left to right โโโบ first failure short-circuitsโ
โ โ โ
โ โโโโบ errors[name] = "message" (invalid) โ
โ โโโโบ errors[name] = undefined (valid) โ
โ โ
โ blur โโโบ meta.touched becomes true โ
โ submit โโโบ every field is re-validated before the call โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Rule Contract
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ RULE FUNCTION โ
โ โ
โ (value, params, ctx) => true | string | Promise โ
โ โ
โ true โ field passes โ
โ "message" โ field fails, message stored in errors โ
โ Promise โ meta.pending true while awaited โ
โ โ
โ ctx.form โ every other field's current value โ
โ ctx.field โ the field name being validated โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Core package | vee-validate (v4 for Vue 3) |
| Rule package | @vee-validate/rules |
| Message package | @vee-validate/i18n |
| Schema adapters | @vee-validate/yup, @vee-validate/zod |
| Form composable | useForm |
| Field composable | useField |
| Field shorthand | defineField โ [ref, attrs] |
| State objects | values, errors, meta |
| Form meta flags | valid, dirty, touched, pending |
| Component surface | <Form>, <Field>, <ErrorMessage> |
Key takeaways:
- Version 4 is the Vue 3 line. It is built on the Composition API, registers rules with
defineRule, and has noextend()or<ValidationProvider>. Version 3 code does not run against it. valuesis a reactive object, not a ref. Destructuring it copies a primitive and silently breaks reactivity; keep the object reference and read properties from it.errorsis keyed by field name andundefinedmeans valid. Server-side messages go into the same record throughsetErrors, so the template never needs a second error source.metaanswers four questions at once.valid,dirty,touched, andpendingare the flags that drive the submit button, the unsaved-changes warning, and the spinner, without any manual booleans.defineFieldreturns a tuple, and both halves matter. The ref drivesv-model; the attrs object carriesnameand the event handlers that trigger validation. Binding only the ref produces a form that never validates.- Rules are plain functions with a fixed contract.
truepasses, a string fails, and a returned promise makes the fieldpendingwhile it resolves. The third argument exposesctx.formfor cross-field checks. - The component API and the composable API share one engine.
<Field>callsuseFieldinternally, so the two styles mix freely inside one<Form>, and both expose the samevalues,errors, andmeta. - Prefill through
resetForm({ values }). Assigning values after creation makes the form dirty on load, which breaks both the unsaved-changes guard and the “untouched” experience.
Remember: VeeValidate is best understood as three reactive objects and a set of functions that keep them in sync with the DOM. values holds the data, errors holds the first failing message per field, and meta holds the lifecycle flags โ valid, dirty, touched, pending. Every rule you write is a function that returns true or a string, and every element of the API, whether a composable or a component, is a different way of reading and writing those three objects. Choose the composable surface when the state needs to be watched, tested, or prefilled; choose the component surface when the form is simple and the layout is the hard part. Both are the same library.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!