| | |

Vue Forms 04 ๐Ÿ“ useForm() & defineField() โ€” Managing Reactive Form State, Blur/Change Behavior, and handleSubmit()

โฑ๏ธ Estimated read: 24 min | |

Two functions carry almost all of the weight in a VeeValidate form. useForm() creates the form context: it allocates the three state buckets, wires up the validation pipeline, and hands back the actions that mutate them. defineField() creates one field inside that context: it returns a pair โ€” a ref to bind with v-model and an attributes object to bind with v-bind โ€” and the attributes object is what attaches the validation triggers to the DOM element.

The pair is deliberately asymmetric. useForm() is called once per form and owns everything; defineField() is called once per input and owns almost nothing. A field does not validate itself. It asks the form context to validate a named value, and the context decides whether the rules run, which rules run, and what the resulting message is. That inversion is why a form with twenty fields does not have twenty validation engines, and why handleSubmit() can validate everything at once without visiting the DOM.

This chapter covers the useForm() options object and what each option changes; the defineField() tuple and the meaning of every option it accepts; the event matrix that decides when a message appears and when it does not; and handleSubmit(), which is a validation gate wrapped around your submission handler rather than a simple submit listener. The behavior of blur, change, and input is treated in its own section because it is the single largest source of “why is my form validating at the wrong time” confusion.

Key point: useForm() owns the state and the validation pipeline, and defineField() owns only the binding between one DOM element and one named value. A field is validated when the context is told to validate it, and handleSubmit() is the one call that tells the context to validate every field at once.


Why These Two Functions Exist

The ownership problem. A hand-written form usually keeps its state in the component that renders it, which works until a child component needs to read or write one value. Then the value gets passed down as a prop and the update comes back as an emit, and the chain grows with each level of nesting. useForm() hoists the state into a context object that any descendant can read through useFormContext(), so a password-strength meter three components deep reads the same values.password the form wrote, with no props and no emits.

The binding problem. The v-model directive does two jobs at once: it writes the value into the ref, and it listens for update:modelValue. It does not listen for blur, and it cannot distinguish an input event from a change event. A form that validates on blur needs the blur handler attached somewhere, and a form that validates on input needs a different listener than one that validates on change. defineField() solves this by returning a second object that contains the event handlers, so v-bind on the element supplies the listeners that v-model alone cannot.

The trigger problem. When validation runs is a product decision, not an implementation detail. Validating a password confirmation on every keystroke fires a red “passwords do not match” while the user is still typing the second password โ€” technically accurate and experientially hostile. Validating only on submit hides every problem until the user has finished. The real answer is per-field: aggressive triggers for cheap checks, lazy triggers for expensive or discouraging ones. defineField() accepts the trigger flags per field, and useForm() accepts them for the whole form, which makes the decision explicit and local.

The submit problem. A submit handler that calls validate() and then runs the API call must handle three cases: validation failed, validation passed but the network failed, and validation passed and the network succeeded. Writing that sequence by hand in every form produces subtle bugs โ€” the button never re-enables on a thrown error, or the second click fires a second request while the first is in flight. handleSubmit() wraps the sequence, tracks isSubmitting while the promise is outstanding, increments submitCount, and calls an optional second handler when validation blocked the submit.

The async problem. An email-uniqueness rule is a network round trip. While it is in flight the form is neither valid nor invalid; it is pending. Without a pending flag, the submit button flickers between enabled and disabled, and optimistic users submit twice. useForm() and each field expose meta.pending, which is true exactly while an asynchronous rule is unresolved, so the UI has a third state it can render instead of guessing.

The trade-off. Two functions and a per-field options object is more ceremony than v-model plus a watch. The ceremony buys three things: one place where state lives, one place where the trigger policy is declared, and one wrapper that makes submission a single atomic decision. Forms that are one input deep do not need it. Forms that submit anything to a server almost always do.


a. useForm() โ€” the context, its options, and its returns

useForm() is called once in the component that owns the form โ€” normally the <script setup> block of the form component itself. It takes an options object and returns an object containing both state and actions.

// src/components/SignupForm.vue
import { useForm } from "vee-validate";

const {
  // --- state ---
  values,            // reactive record: { email: "", password: "" }
  errors,            // reactive record: { email?: "message" }
  meta,              // { valid, dirty, touched, pending, initialValues }
  isSubmitting,      // ref<boolean>, true while handleSubmit's handler awaits
  submitCount,       // ref<number>, incremented on every submit attempt
  controlledValues,  // computed view of values, same content

  // --- actions ---
  defineField,       // (name, rules?, opts?) => [ref, attrs]
  handleSubmit,      // (handler, onInvalid?) => submitHandler
  handleReset,       // resets values, errors, and touched in one call
  resetForm,         // granular reset: { values, errors, touched }
  validate,          // validates every field, returns a summary
  validateField,     // validates one field by name
  setFieldValue,     // writes one value through the field bookkeeping
  setValues,         // writes many values at once
  setFieldError,     // injects one message (server errors)
  setErrors,         // injects many messages
  setFieldTouched,   // marks one field touched
  setTouched,        // marks many fields touched
} = useForm({
  initialValues: { email: "", password: "", acceptTerms: false },
  validateOnMount: false,   // do not mark the empty form red on first paint
});

The options object has four members that matter day to day. initialValues sets the baseline for both values and meta.dirty โ€” the dirty flag is computed by comparing each current value against its initial value, so a form pre-filled by mutation after creation is permanently dirty. validateOnMount decides whether the first render runs the rules; the default is false, which is why a fresh form shows no error text until the user interacts. keepValuesOnUnmount preserves a field’s value after its component unmounts, which is what multi-step wizards need so that going back a step does not erase what was typed. validationSchema attaches a whole-form schema instead of per-field rules and is covered in a later chapter.

// A wizard step: fields unmount when the step changes
const form = useForm({
  initialValues: { email: "", plan: "", card: "" },
  keepValuesOnUnmount: true, // step 1 values survive the step 2 render
});

Actions that write state exist because writing to values or errors directly skips bookkeeping. setFieldValue updates the value and lets the field’s watchers and dirty comparison observe the change; setFieldError puts a message into errors without pretending a rule produced it, which is exactly what a server response needs.

// Server rejected the email: put the message where the template reads it
async function register(payload) {
  const res = await fetch("/api/users", { method: "POST", body: JSON.stringify(payload) });
  if (res.status === 409) {
    setFieldError("email", "This email is already registered.");
    setFieldTouched("email", true); // so the message is not hidden by a touched check
    return;
  }
}

resetForm and handleReset are not the same call. handleReset() restores the values captured at creation, clears every error, and clears every touched flag. resetForm(opts) takes an object and lets you reset one part at a time โ€” passing only values rewrites the current values and the baseline together, which is how a profile form is loaded from an API without appearing dirty.

// Rewrites current AND initial values, so meta.dirty stays false
resetForm({ values: { email: user.email, password: "", acceptTerms: false } });

// Clears errors only, leaving values untouched
resetForm({ errors: {} });

b. defineField() โ€” the tuple, the attributes, and the options

defineField(name, rules?, opts?) returns a two-element tuple. The first element is a writable ref bound to the field’s value; the second is a plain object of attributes to spread onto the element.

// Tuple destructuring: [valueRef, attrsObject]
const [email, emailAttrs] = defineField("email", "required|email");
const [password, passwordAttrs] = defineField("password", "required|min:8");
<template>
  <form @submit="onSubmit">
    <!-- The ref carries the value; the attrs carry the listeners -->
    <input v-model="email" v-bind="emailAttrs" type="email" />
    <p v-if="errors.email">{{ errors.email }}</p>

    <input v-model="password" v-bind="passwordAttrs" type="password" />
    <p v-if="errors.password">{{ errors.password }}</p>
  </form>
</template>

The attributes object contains name โ€” so the element is identifiable in the DOM and in the errors record โ€” plus the onInput, onChange, and onBlur handlers that forward the DOM events into the form context. If syncVModel is enabled, it also carries onUpdate:modelValue, which lets <Field v-model="..."> style two-way binding work against the field rather than the component.

// syncVModel adds the model-value listener to the attrs
const [country, countryAttrs] = defineField("country", "required", {
  syncVModel: true, // attrs now include "onUpdate:modelValue"
});

The second argument is the rule expression: a string in pipe syntax, an array of rule functions, or a function. Rule functions can be mixed into the array without being registered globally, which is the right choice for a check that exists in one component.

// A local rule alongside a registered one
const notDisposable = (v) =>
  !/@(mailinator|tempmail)\./i.test(v) || "Please use a permanent address";

const [email, emailAttrs] = defineField("email", ["required", "email", notDisposable]);

When the second argument is an options object rather than a rule, VeeValidate treats it as the options and assumes no rules were given. This is why defineField("email", { validateOnInput: true }) reads naturally even though the rules are simply omitted โ€” a form-level validationSchema is expected to supply them.

// No rules here: the form-level schema does the validating
const [email, emailAttrs] = defineField("email", { validateOnInput: true });

For checkboxes and radios, the type must be declared so the field writes the right value shape. A group of checkboxes sharing one field name writes an array, and checkedValue tells the field which value each box contributes.

// A single boolean checkbox: writes true/false
const [accept, acceptAttrs] = defineField("acceptTerms", "required", {
  type: "checkbox",
});

// A group: every checked box appends its checkedValue to the array
const [plans, plansAttrs] = defineField("plans", "required", {
  type: "checkbox",
  checkedValue: "pro", // this box contributes the string "pro"
});
<input v-model="accept" v-bind="acceptAttrs" type="checkbox" />
<label>I accept the terms</label>

<input v-model="plans" v-bind="plansAttrs" type="checkbox" value="pro" />
<label>Pro plan</label>

Two siblings exist for cases the tuple does not fit. defineInputBinds(name, rules?, opts?) returns a single props object rather than a tuple, which is convenient when you want to spread everything at once and read the value from values instead of a local ref. defineComponentBinds(name, config?) returns a props object shaped for a custom component โ€” modelValue plus onUpdate:modelValue โ€” and accepts a mapProps function so its keys can be renamed to match a component that uses something other than modelValue.

// For a component that calls its value "selected" instead of "modelValue"
const dateBinds = defineComponentBinds("startDate", {
  mapProps: (state) => ({ selected: state.value, onSelect: state.onInput }),
});

c. Blur, change and input โ€” what actually triggers validation

The DOM emits three relevant events, and VeeValidate maps each to a separate flag. Understanding the difference between them is the difference between a form that feels considered and one that feels broken.

The input event fires on every keystroke. The change event fires for a text input when the value has been modified and the element loses focus; for a <select> and for a checkbox it fires immediately. The blur event fires when the element loses focus, whether or not anything changed. The default configuration is validateOnChange: true, validateOnBlur: true, validateOnInput: false, validateOnModelUpdate: true, and validateOnMount: false. So a plain text input validates when the user leaves it, not while they type.

// Default behaviour: the message appears when the user leaves the box
const [email, emailAttrs] = defineField("email", "required|email");

// Aggressive: the message appears on the first keystroke
const [username, usernameAttrs] = defineField("username", "required|min:3", {
  validateOnInput: true,
});

The choice is a UX decision with a technical constraint attached. Validating on input is responsive and correct for a username with a live availability check, because the user expects immediate feedback on every character. It is discouraging for a password strength rule, because the first two keystrokes always fail and the user sees red before they have had a chance to type. Validating on change gives feedback after the user has committed to a value, which is the sensible default for most fields.

// Expensive or async checks belong on blur/change, never on input
const [email, emailAttrs] = defineField("email", "required|email|unique_email", {
  validateOnInput: false,  // no API call per keystroke
  validateOnChange: true,  // one check when the user leaves the field
});

blur does double duty. It triggers validation if validateOnBlur is on, and it always sets meta.touched to true for that field. The touched flag is what lets a template show a message only after the user has engaged, which avoids the “red form on first paint” problem without turning validation off entirely.

// Field-level meta drives the timing of the message, not just its text
const { value, errorMessage, meta: fieldMeta, handleBlur, handleChange } =
  useField("email", "required|email", { initialValue: "" });
<!-- Message shown only after the user has left the field once -->
<p v-if="fieldMeta.touched && errorMessage">{{ errorMessage }}</p>

validateOnModelUpdate applies to custom components rather than native elements. A third-party combobox emits update:modelValue and may not emit a usable blur at all, so the only signal available is the model update, and this flag makes that signal trigger validation. Setting it on a native input is harmless but redundant, since the input and change handlers already cover it.

// A date picker that only emits update:modelValue
const [when, whenAttrs] = defineField("when", "required", {
  validateOnModelUpdate: true, // the only signal this component provides
});

The form-level flags set the default for every field, and a field-level flag overrides it for that field alone. Setting validateOnInput: true on the form and false on the one async field is the standard combination: responsiveness everywhere, one exception where a network call would be wasteful.


d. handleSubmit() โ€” the validation gate and the submitting state

handleSubmit(handler, onInvalid?) does not attach a listener. It returns a function that you bind to the form’s submit event, and that function performs a fixed sequence: validate every field, then either run your handler with the validated values or run the optional invalid handler with the errors.

// The returned function is what the form's @submit binds to
const onSubmit = handleSubmit(
  async (validatedValues, actions) => {
    // Runs only when every field passed validation
    await api.createAccount(validatedValues);
  },
  ({ errors, values, evt }) => {
    // Runs only when validation blocked the submit
    const firstInvalid = Object.keys(errors)[0];
    document.querySelector(`[name="${firstInvalid}"]`)?.focus();
  }
);
<form @submit="onSubmit" novalidate>
  <!-- novalidate disables the browser's own bubble validation -->
</form>

isSubmitting is true from the moment your handler is invoked until the promise it returns settles, whether it resolves or rejects. That flag is what disables the button during the request, and it is also what makes a thrown error safe: the flag returns to false on rejection too, so a failed request does not leave the form permanently locked.

// The button reflects both validation state and in-flight state
const canSubmit = computed(() => !isSubmitting.value && !meta.pending);
<button type="submit" :disabled="!canSubmit">
  {{ isSubmitting ? "Creating accountโ€ฆ" : "Create account" }}
</button>

submitCount increments on every attempt, including blocked ones. It is the standard way to reveal errors for a form the user has already tried to submit: show a field’s message when the field is touched, or when the submit count is greater than zero.

// A common pattern: after one submit attempt, show all messages
const showAll = computed(() => submitCount.value > 0);

The handler’s second argument is a set of form actions, which means the submission code can report server-side failures without closing over the form object. setFieldError puts a message into the same errors record the template reads, so a server rejection looks identical to a client-side rule failure.

const onSubmit = handleSubmit(async (values, { setFieldError, setFieldTouched, resetForm }) => {
  const res = await api.register(values);
  if (!res.ok) {
    setFieldError("email", res.message); // appears under the email input
    setFieldTouched("email", true);      // and is not hidden by a touched guard
    return;                              // isSubmitting still resets to false
  }
  resetForm();                           // clear values, errors, and touched
});

The invalid handler receives { errors, values, results, evt }. errors is the field-to-message record; results is the per-field validation result, which is what you inspect when a rule returned structured data rather than a string. Ignoring the second argument entirely is fine โ€” a submit that silently does nothing when invalid is a valid choice, provided the messages are already visible.

// Inspecting a richer rule result rather than a plain message
const onSubmit = handleSubmit(handler, ({ results }) => {
  const first = Object.values(results).find((r) => !r.valid);
  analytics.track("form_blocked", { reason: first?.errors?.[0] });
});

Complete Example Session

// ============================================
// PART 1: THE FORM CONTEXT AND ITS BASELINE
// ============================================
// src/components/SignupForm.vue โ€” <script setup>
import { computed } from "vue";
import { useForm } from "vee-validate";

const {
  values, errors, meta, isSubmitting, submitCount,
  defineField, handleSubmit, resetForm, setFieldError, setFieldTouched,
} = useForm({
  // The baseline that meta.dirty compares against
  initialValues: { name: "", email: "", password: "", plan: "", terms: false },
  validateOnMount: false, // no red text before the user types
});

// ============================================
// PART 2: A FIELD WITH DEFAULT TRIGGERS
// ============================================
// No options: validates on change and blur, not on every keystroke
const [name, nameAttrs] = defineField("name", "required|min:2");

// ============================================
// PART 3: A FIELD THAT VALIDATES AS YOU TYPE
// ============================================
// validateOnInput overrides the form default for this field only
const [email, emailAttrs] = defineField("email", "required|email", {
  validateOnInput: true,  // immediate feedback on a cheap local check
  validateOnChange: true, // and again when the user leaves the box
});

// ============================================
// PART 4: A FIELD WITH A LOCAL RULE
// ============================================
// Rules can be inline functions mixed with registered rule names
const strong = (v) =>
  (/[A-Z]/.test(v) && /\d/.test(v)) || "Use at least one capital and one digit";

const [password, passwordAttrs] = defineField("password", ["required", "min:8", strong], {
  validateOnInput: false, // a strength rule on every keystroke is punishing
});

// ============================================
// PART 5: A SELECT AND A CHECKBOX
// ============================================
const [plan, planAttrs] = defineField("plan", "required"); // <select>

const [terms, termsAttrs] = defineField("terms", "required", {
  type: "checkbox", // writes a boolean, not a string
});

// ============================================
// PART 6: META-DRIVEN UI
// ============================================
// Every disabled state is derived, never stored
const showAllErrors = computed(() => submitCount.value > 0);
const canSubmit = computed(() => meta.valid && !meta.pending && !isSubmitting.value);
const unsaved = computed(() => meta.dirty && !meta.valid);

// ============================================
// PART 7: THE SUBMIT HANDLER
// ============================================
const onSubmit = handleSubmit(async (validated, { setFieldError, resetForm }) => {
  // This block runs only if validate() passed for every field
  const res = await fetch("/api/signup", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(validated),
  });

  if (res.status === 409) {
    // Server says the email is taken: reuse the local errors record
    setFieldError("email", "This email is already registered.");
    return; // isSubmitting flips back to false automatically
  }

  resetForm(); // values, errors, and touched all return to baseline
});

// ============================================
// PART 8: THE INVALID BRANCH
// ============================================
const onSubmitWithFocus = handleSubmit(handler, ({ errors: invalid }) => {
  // Focus the first failing control so the user lands on the problem
  const first = Object.keys(invalid)[0];
  document.querySelector(`[name="${first}"]`)?.focus();
});

// ============================================
// PART 9: PROGRAMMATIC VALUE WRITES
// ============================================
function applyCoupon(code) {
  // setFieldValue keeps dirty tracking and watchers consistent;
  // assigning values.plan directly would bypass them
  setFieldValue("plan", code === "PRO50" ? "pro" : "free");
}

// ============================================
// PART 10: PREFILL FROM AN API
// ============================================
async function loadProfile() {
  const user = await api.me();
  // resetForm({ values }) rewrites current AND initial values,
  // so the form loads without appearing dirty
  resetForm({ values: { ...values, name: user.name, email: user.email } });
}
<!-- The template that binds all ten parts together -->
<template>
  <form novalidate @submit="onSubmitWithFocus">
    <label>Name
      <input v-model="name" v-bind="nameAttrs" />
    </label>
    <p v-if="(showAllErrors || nameAttrs) && errors.name">{{ errors.name }}</p>

    <label>Email
      <input v-model="email" v-bind="emailAttrs" type="email" />
    </label>
    <p v-if="errors.email">{{ errors.email }}</p>

    <label>Password
      <input v-model="password" v-bind="passwordAttrs" type="password" />
    </label>
    <p v-if="errors.password">{{ errors.password }}</p>

    <select v-model="plan" v-bind="planAttrs">
      <option value="">Choose a plan</option>
      <option value="free">Free</option>
      <option value="pro">Pro</option>
    </select>

    <label>
      <input v-model="terms" v-bind="termsAttrs" type="checkbox" />
      I accept the terms
    </label>
    <p v-if="errors.terms">{{ errors.terms }}</p>

    <button type="submit" :disabled="!canSubmit">
      {{ isSubmitting ? "Creatingโ€ฆ" : "Create account" }}
    </button>
    <span v-if="unsaved">Unsaved changes</span>
  </form>
</template>

The ten parts covered the form context, a default-trigger field, an input-triggered field, an inline rule, a select and a checkbox, meta-derived UI, the submit handler, the invalid branch, programmatic writes, and a dirty-free prefill.


Quick Reference

useForm() Options

OptionDefaultEffect
initialValues{}Baseline for values and meta.dirty
validateOnMountfalseRun rules on first render
keepValuesOnUnmountfalsePreserve values after a field unmounts
validationSchemaundefinedWhole-form schema instead of per-field rules

defineField() Options

OptionDefaultEffect
initialValue""Starting value for this field
validateOnInputfalseValidate on every keystroke
validateOnChangetrueValidate on the DOM change event
validateOnBlurtrueValidate when the element loses focus
validateOnModelUpdatetrueValidate on update:modelValue
typeundefinedcheckbox or radio value handling
checkedValuetrueValue a checkbox contributes to the array
syncVModelfalseAdd onUpdate:modelValue to the attrs

The Returned Tuple

ElementTypeBind with
[0] valuewritable Refv-model
[1] attrsplain objectv-bind

handleSubmit() Behaviour

MemberMeaning
First argumentReceives validated values and form actions
Second argumentReceives { errors, values, results, evt }
isSubmittingtrue while the handler’s promise is unresolved
submitCountIncremented on every attempt, blocked ones included

Best Practices

โœ… Do This:

// Spread the attrs so the triggers are attached
<input v-model="email" v-bind="emailAttrs" />                    // โœ…

// Turn input validation on for cheap local checks
defineField("email", "required|email", { validateOnInput: true }); // โœ…

// Keep input validation off for async or discouraging rules
defineField("email", rules, { validateOnInput: false });          // โœ…

// Derive every disabled state from meta and isSubmitting
const canSubmit = computed(() => meta.valid && !isSubmitting.value); // โœ…

// Report server failures through setFieldError
setFieldError("email", "Already registered");                     // โœ…

// Prefill through resetForm so the form is not dirty
resetForm({ values: fetched });                                   // โœ…

// Bind the submit through handleSubmit, not a raw listener
<form @submit="handleSubmit(onSave)">                             // โœ…

โŒ Don’t Do This:

// Binding the ref without the attrs leaves validation unwired
<input v-model="email" />                                         // โŒ

// Validating an API-backed rule on every keystroke
defineField("email", "unique", { validateOnInput: true });        // โŒ

// A manual submitting flag that drifts from the real state
const loading = ref(false);                                       // โŒ

// Writing to the errors record directly
errors.email = "nope";                                            // โŒ

// Assigning values after useForm and expecting dirty to be false
values.email = user.email;                                        // โŒ

// Calling the submit handler directly, bypassing validation
<button @click="onSave(values)">                                  // โŒ

// Leaving the browser's own validation bubbles enabled
<form @submit="onSubmit">                                         // โŒ

Common Pitfalls

PitfallWhy It HappensFix
A field never validatesAttrs from defineField not boundAdd v-bind="attrs"
Everything turns red on loadvalidateOnMount: trueLeave it false
Message flickers while typingvalidateOnInput on a slow ruleSet it false for that field
Button stuck after an errorManual loading flag not resetUse isSubmitting
Form is dirty immediatelyValues assigned after creationresetForm({ values })
Checkbox writes a stringMissing type: "checkbox"Declare the type
Wizard loses values on backFields unmount between stepskeepValuesOnUnmount: true
Double submissionRaw listener instead of handleSubmitGuard on isSubmitting

Real-World Examples

1. Default trigger field

const [name, nameAttrs] = defineField("name", "required");

2. Input-triggered field

const [email, emailAttrs] = defineField("email", "required|email", {
  validateOnInput: true,
});

3. Async rule kept off input

const [email, a] = defineField("email", "unique", { validateOnInput: false });

4. Checkbox group

const [plans, plansAttrs] = defineField("plans", "required", { type: "checkbox" });

5. Preventing values loss in a wizard

useForm({ initialValues: {}, keepValuesOnUnmount: true });

6. Submit bound through the wrapper

const onSubmit = handleSubmit((v) => api.save(v));

7. Submit button state

const canSubmit = computed(() => meta.valid && !isSubmitting.value);

8. Server error injection

setFieldError("email", "Already registered");
setFieldTouched("email", true);

9. Focus the first invalid control

handleSubmit(save, ({ errors }) => {
  document.querySelector(`[name="${Object.keys(errors)[0]}"]`)?.focus();
});

10. Dirty-free prefill

resetForm({ values: await api.me() });

Visual

What Each Function Owns

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  useForm()                    defineField()                โ”‚
โ”‚  โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€                    โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€                โ”‚
โ”‚  owns the form context        owns one field               โ”‚
โ”‚  values, errors, meta         ref + attrs pair             โ”‚
โ”‚  handleSubmit, resetForm      validation triggers          โ”‚
โ”‚  shared across fields         one per input                โ”‚
โ”‚                                                            โ”‚
โ”‚  Both call the same store โ”€โ”€โ–บ values / errors / meta       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Trigger Matrix

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  EVENT            OPTION                 DEFAULT   FIRES?  โ”‚
โ”‚  โ”€โ”€โ”€โ”€โ”€            โ”€โ”€โ”€โ”€โ”€โ”€                 โ”€โ”€โ”€โ”€โ”€โ”€โ”€   โ”€โ”€โ”€โ”€โ”€โ”€  โ”‚
โ”‚  input            validateOnInput        false     no      โ”‚
โ”‚  change           validateOnChange       true      yes     โ”‚
โ”‚  blur             validateOnBlur         true      yes     โ”‚
โ”‚  v-model update   validateOnModelUpdate  true      yes     โ”‚
โ”‚  mount            validateOnMount        false     no      โ”‚
โ”‚                                                            โ”‚
โ”‚  change fires when a text box loses focus after editing    โ”‚
โ”‚  input  fires on every keystroke                           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Submission Sequence

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  submit event                                              โ”‚
โ”‚      โ”‚                                                     โ”‚
โ”‚      โ–ผ                                                     โ”‚
โ”‚  handleSubmit wraps your handler                           โ”‚
โ”‚      โ”‚                                                     โ”‚
โ”‚      โ–ผ                                                     โ”‚
โ”‚  validate() runs every field                               โ”‚
โ”‚      โ”‚                                                     โ”‚
โ”‚      โ”œโ”€โ”€ invalid โ”€โ”€โ–บ onInvalid({ errors }) โ”€โ”€โ–บ stop        โ”‚
โ”‚      โ”‚                                                     โ”‚
โ”‚      โ””โ”€โ”€ valid   โ”€โ”€โ–บ isSubmitting = true                   โ”‚
โ”‚                      await your handler(values, actions)    โ”‚
โ”‚                      isSubmitting = false                  โ”‚
โ”‚                      submitCount++                         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The defineField Tuple

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  const [email, emailAttrs] = defineField("email", "email") โ”‚
โ”‚          โ”‚      โ”‚                                          โ”‚
โ”‚          โ”‚      โ””โ”€โ”€ attrs: name, onInput, onChange, onBlur โ”‚
โ”‚          โ”‚           spread with v-bind onto the element   โ”‚
โ”‚          โ”‚                                                 โ”‚
โ”‚          โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ ref: bind with v-model                 โ”‚
โ”‚                                                            โ”‚
โ”‚  <input v-model="email" v-bind="emailAttrs" />             โ”‚
โ”‚      โ–ฒ                   โ–ฒ                                 โ”‚
โ”‚      โ”‚                   โ””โ”€โ”€ triggers validation           โ”‚
โ”‚      โ””โ”€โ”€ carries the value out and in                      โ”‚
โ”‚                                                            โ”‚
โ”‚  Both halves are required. The ref alone never validates.  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Context creatoruseForm(options?)
Field creatordefineField(name, rules?, opts?)
Tuple[valueRef, attrsObject]
State bucketsvalues, errors, meta
Form metavalid, dirty, touched, pending
In-flight flagisSubmitting
Attempt countersubmitCount
Submit wrapperhandleSubmit(handler, onInvalid?)
Reset callshandleReset(), resetForm(opts)
Value writerssetFieldValue, setValues
Error writerssetFieldError, setErrors

Key takeaways:

  • useForm() owns the state; defineField() owns the binding. The field does not run its own rules โ€” it forwards events into the context, and the context decides what runs and records the message.
  • The tuple has two halves and both are mandatory. The ref carries the value through v-model; the attrs object carries name and the DOM listeners through v-bind. Binding only the ref produces a field that never validates.
  • The defaults validate on change and blur, not on input. A text input therefore reports its first message when the user leaves it, which is the least hostile default and the reason validateOnInput is opt-in.
  • Trigger flags are per-field and override the form. Turn validateOnInput on for a cheap local check and off for an API-backed or discouraging rule; the two fields can coexist in one form without conflict.
  • handleSubmit() is a gate, not a listener. It validates everything first, runs your handler only on success, and calls the optional second handler with the errors when validation blocked the submit.
  • isSubmitting is the only honest loading flag. It is true while your handler’s promise is unresolved and returns to false on rejection as well as resolution, so a failed request never leaves the button locked.
  • Server errors belong in the same record as rule errors. setFieldError and setErrors write into errors, so the template has one source of truth and the error styling stays consistent.
  • Prefill through resetForm({ values }). Assigning to values after creation leaves the baseline untouched, which makes the form permanently dirty and breaks every unsaved-changes guard built on meta.dirty.

Remember: useForm() builds the container and defineField() plugs elements into it. The container holds values, errors, and meta, and every UI decision in a form is a read of one of those three objects. The plug decides when events reach the container โ€” that is what the trigger options control โ€” and handleSubmit() is the single moment where all the fields are checked at once before your code runs. Change the trigger flags, not the validation logic, when a form feels wrong to use; change the options object, not the component, when the state needs a different baseline.

Was this helpful?


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!