| | |

Vue Forms 06 📝 Custom Form Inputs with useField() — Connecting custom UI library components (Tailwind/Headless UI) to VeeValidate

⏱️ Estimated read: 8 min | |

Modern Vue development relies heavily on component libraries and custom UI components built with tools like Tailwind CSS and Headless UI. While VeeValidate’s standard <Field> component works seamlessly for basic HTML tags, it often becomes restrictive when you need to integrate complex, headless components that manage their own internal state or require custom event handling. This is where useField becomes the essential bridge between your component library and your validation logic.

The useField composition function provides the building blocks for custom validation. It exposes reactive values for the field’s current state, including value, errorMessage, meta data, and methods like validate and handleChange. By utilizing useField inside your own wrapper components, you can maintain the styling flexibility of Tailwind and the accessibility features of Headless UI while inheriting the robust validation engine of VeeValidate.

This chapter explores how to abstract validation logic into reusable wrappers. We will look at how to initialize fields using useField, how to bind that state to custom UI components, and how to synchronize internal input events with VeeValidate’s reactive system to ensure your forms remain both visually appealing and perfectly validated.

Key point: useField is the underlying engine of VeeValidate that allows you to turn any component—regardless of its complexity—into a validated field by providing reactive bindings for values, error handling, and manual validation triggering.


Why useField exists

Why useField exists

The Component Library Problem. Many modern UI libraries are built to be “headless,” providing logic without opinionated styling. Integrating standard <Field> tags into these components often leads to prop-drilling hell or loss of encapsulation where the parent form must know too much about the internal input structure.

The State Synchronization Problem. Custom components often manage internal local state for debouncing, complex input masks, or specific UI library patterns (like Headless UI’s Switch). useField allows you to treat these internal states as the “source of truth” while keeping the validation engine updated.

The Design System Constraint. When you wrap components in a company-wide design system, you cannot inject extra props into the underlying inputs. useField allows you to create an encapsulated <MyStyledInput /> that handles its own validation internally, keeping the implementation code clean and dry.

The Validation Logic Decoupling. By placing useField inside a child component, the parent form doesn’t need to know how to handle errors or input changes. The child handles its own errorMessage and meta state, making the form component purely focused on structure and submission.

The Interoperability Requirement. Some third-party components don’t emit standard native input or change events. useField provides handleChange and handleBlur helpers that you can bind to any event type or method, allowing for total control over when validation occurs.


a. The useField composition function

The useField function is the core primitive. You invoke it within a Vue component’s setup() or <script setup> block. It requires a name for the field, which acts as the key for validation tracking, and optionally, a validation rule or a configuration object.

import { useField } from 'vee-validate';

const { value, errorMessage, meta } = useField('email', (value) => {
  return value ? true : 'This field is required';
});

The function returns a reactive object containing the field’s state. value is a ref that you can bind to your custom component. When you update value, VeeValidate automatically runs the provided validation rule and updates the errorMessage and meta states.


b. Binding with v-model and validation events

To make a component “VeeValidate-aware,” you map the value and events from useField to your component’s props. For simple components, you can pass value directly to v-model or use it to update the internal component state.

// Inside a wrapper component
const props = defineProps(['name', 'modelValue']);
const { value, handleBlur, handleChange } = useField(props.name);

// Sync value with parent if using v-model
watch(() => props.modelValue, (newVal) => {
  value.value = newVal;
});

You must explicitly call handleChange or handleBlur to trigger validation. VeeValidate does not automatically track internal DOM events inside custom components unless you wire them up. This provides the granularity required for custom UI components that might not emit standard DOM events.


c. Bridging with headless components

Headless UI components are often purely declarative, requiring you to handle the data flow manually. useField acts as the bridge that manages the lifecycle of the value and the associated errors, which you then pass into the headless component via props.

// Using Headless UI Switch
const { value, handleChange } = useField('isSubscribed');

<Switch 
  :model-value="value" 
  @update:model-value="handleChange" 
/>

By passing handleChange directly to the custom component’s update event, you ensure that VeeValidate captures every change accurately. This pattern works for any library, whether it is Tailwind-styled inputs, Headless UI switches, or complex rich-text editors, because you are explicitly controlling the input loop.


Complete Example Session

// ============================================
// PART 1: COMPONENT SETUP
// ============================================
import { useField } from 'vee-validate';
import { defineProps } from 'vue';

const props = defineProps(['name', 'rules']);
const { value, errorMessage, meta, handleBlur } = useField(props.name, props.rules);

// ============================================
// PART 2: UI BINDING
// ============================================
// value is reactive and linked to the form
// errorMessage reactive displays errors

// ============================================
// PART 3: HEADLESS INTEGRATION
// ============================================
// <input :value="value" @input="handleChange" @blur="handleBlur" />

// ============================================
// PART 4: ERROR DISPLAY
// ============================================
// <span v-if="errorMessage">{{ errorMessage }}</span>

// ============================================
// PART 5: META STATE
// ============================================
// <div :class="{'border-red-500': meta.touched && !meta.valid}">

// ============================================
// PART 6: FORM SUBMISSION
// ============================================
// Handled by parent form using useForm

// ============================================
// PART 7: CUSTOM RULES
// ============================================
// rules passed as props to useField

// ============================================
// PART 8: REUSABILITY
// ============================================
// Wrapper can be used anywhere in the app

// ============================================
// PART 9: INITIALIZATION
// ============================================
// useField(props.name, props.rules)

// ============================================
// PART 10: CLEANUP
// ============================================
// VeeValidate unregisters field on unmount

This sequence creates a robust, reusable component wrapper that encapsulates validation logic, error display, and state management, providing a cleaner interface for the parent form.


Quick Reference

The useField Return Object

KeyTypeDescription
valueRef<any>The current value of the field
errorMessageRef<string>The error message
metaObjectReactive state (dirty, touched, valid)
handleChangeFunctionTrigger validation manually
handleBlurFunctionTrigger blur validation

Configuration Options

OptionTypeEffect
initialValueanyStarting value of the field
validateOnValueUpdatebooleanValidate on input changes
syncVModelbooleanAutomatically sync with v-model

Meta Object Properties

PropertyDescription
validIs the field currently passing?
dirtyHas the user interacted with it?
touchedHas the field been blurred?
pendingIs an async validation running?

Best Practices

✅ Do This:

// Keep validation logic in the wrapper component
const { value } = useField(props.name, props.rules);          // ✅

// Expose meta for styling
const { meta } = useField(props.name);                        // ✅

// Use handleBlur for better UX
<input @blur="handleBlur" />                                  // ✅

// Destructure return object
const { value, errorMessage } = useField(props.name);         // ✅

❌ Don’t Do This:

// Don't instantiate useField in loops
useField(loopItem.name);                                      // ❌

// Don't ignore the meta state for styling
<input class="border-gray-300" />                             // ❌

// Don't manual validation inside templates
<input @input="validate()" />                                 // ❌

// Don't overcomplicate initial values
const { value } = useField(name, null, { initialValue: val });// ❌

Common Pitfalls

PitfallWhy It HappensFix
No Error MsgComponent not binding errorMessageBind to template ref
Sync Lagv-model mismatchUse handleChange directly
Re-render loopsuseField inside setupEnsure unique names
Validation blockedManual trigger missingCall handleBlur
Initial value lostComponent lifecyclePass in options object

Real-World Examples

1. Tailwind Styled Text Input

const { value, errorMessage } = useField(props.name);
<input v-model="value" class="border p-2 rounded" />

2. Headless UI Switch

const { value, handleChange } = useField(props.name);
<Switch v-model="value" @update:model-value="handleChange" />

3. Custom Radio Group

const { value, handleChange } = useField(props.name);
<Radio @click="handleChange(opt.val)" />

4. Async Validation

const { value } = useField(name, async (val) => await checkDB(val));

5. Manual Error Injection

const { errorMessage } = useField(name);
errorMessage.value = "Server error";

6. Disabling Validation

const { validate } = useField(name);
// call validate() conditionally

7. Reactive Initial Value

const { value } = useField(props.name, undefined, { initialValue: props.init });

8. Resetting State

const { resetField } = useField(name);
resetField();

9. Custom Error Mapping

const { errorMessage } = useField(name);
// computed(() => translate(errorMessage.value))

10. Form context usage

const { value } = useField(props.name);
// Uses form context if available

Visual

The useField Binding Flow

┌──────────────────────────────────────────────────────────────┐
│  VUE COMPONENT (Custom Input)                                │
│                                                              │
│  useField('name') ──► Internal State (Value/Errors)          │
│         │                                                    │
│         ▼                                                    │
│  Template (HTML Input/Headless Component)                    │
│         │                                                    │
│  Event (Blur/Change) ──► Validation Engine                   │
│                                                              │
└──────────────────────────────────────────────────────────────┘

State Propagation

┌──────────────────────────────────────────────────────────────┐
│  VeeValidate Store                                           │
│         │                                                    │
│         ▼                                                    │
│  useField (Return Object)                                    │
│         │                                                    │
│         ├─► value (Bound to Input)                           │
│         └─► errorMessage (Bound to UI)                       │
└──────────────────────────────────────────────────────────────┘

Custom Component Bridge

┌──────────────────────────────────────────────────────────────┐
│  Parent Form                                                 │
│      │                                                       │
│      ▼                                                       │
│  <ValidatedInput name="email" />                             │
│      │                                                       │
│  <ValidatedInput> (Internal)                                 │
│      │                                                       │
│  useField() ──► Syncs logic & UI                             │
└──────────────────────────────────────────────────────────────┘

Summary

ItemValue
FunctionuseField
Primary Inputname
Return TypeReactive Object
Error StateerrorMessage
InteractionhandleBlur
LogicDecoupled
StylingFlexible

Key takeaways:

  • useField decouples validation. It allows you to create custom inputs that maintain their own internal state and UI library styling.
  • State synchronization is manual. You must wire up events like blur and input to VeeValidate methods to trigger validation cycles correctly.
  • Use meta for styling. The meta object provides real-time information about whether the field is touched or dirty, essential for conditional styling.
  • Headless components work well. By treating the headless component as a data-binding target for value and handleChange, you maintain full control.
  • Rules can be dynamic. You can pass rules to useField at runtime, allowing for highly complex forms with conditional logic.

Remember: useField is the most powerful tool for custom form building in Vue. By encapsulating validation inside your components, you build a cleaner, more maintainable codebase that isolates form logic from UI layout. This approach ensures that your forms are consistent, accessible, and easily testable, regardless of the UI libraries or styling strategies you employ.

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!