Vue Forms 06 📝 Custom Form Inputs with useField() — Connecting custom UI library components (Tailwind/Headless UI) to VeeValidate
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
| Key | Type | Description |
|---|---|---|
value | Ref<any> | The current value of the field |
errorMessage | Ref<string> | The error message |
meta | Object | Reactive state (dirty, touched, valid) |
handleChange | Function | Trigger validation manually |
handleBlur | Function | Trigger blur validation |
Configuration Options
| Option | Type | Effect |
|---|---|---|
initialValue | any | Starting value of the field |
validateOnValueUpdate | boolean | Validate on input changes |
syncVModel | boolean | Automatically sync with v-model |
Meta Object Properties
| Property | Description |
|---|---|
valid | Is the field currently passing? |
dirty | Has the user interacted with it? |
touched | Has the field been blurred? |
pending | Is 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
| Pitfall | Why It Happens | Fix |
|---|---|---|
| No Error Msg | Component not binding errorMessage | Bind to template ref |
| Sync Lag | v-model mismatch | Use handleChange directly |
| Re-render loops | useField inside setup | Ensure unique names |
| Validation blocked | Manual trigger missing | Call handleBlur |
| Initial value lost | Component lifecycle | Pass 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
| Item | Value |
|---|---|
| Function | useField |
| Primary Input | name |
| Return Type | Reactive Object |
| Error State | errorMessage |
| Interaction | handleBlur |
| Logic | Decoupled |
| Styling | Flexible |
Key takeaways:
useFielddecouples 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
blurandinputto VeeValidate methods to trigger validation cycles correctly. - Use
metafor styling. Themetaobject provides real-time information about whether the field istouchedordirty, essential for conditional styling. - Headless components work well. By treating the headless component as a data-binding target for
valueandhandleChange, you maintain full control. - Rules can be dynamic. You can pass rules to
useFieldat 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.
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!