Skip to content

Input Error Directives ​

v-input-error ​

A custom Vue directive to visually display input validation errors by appending an error message and styling the input field with red borders.


Props (Binding Value) ​

TypeRequiredExampleDescription
stringNo'This field is required'The error message to show. If falsy, error styles and messages are removed.

Bound using v-input-error="errorMessage" where errorMessage is a string or falsy.


Slots ​

N/A (used as a directive, not a component).


Emits ​

None (directives do not emit events).


Functions ​

handleErrorMount(el, binding) ​

  • Triggered on initial mount.
  • If binding.value exists:
    • Finds the target input elements (input and .multiselect__tags for Multiselect components) inside el.
    • Adds the .input-error class to the targets.
    • Appends an error <span> with classes field-error and error-message containing the error message.

handleErrorUpdate(el, binding) ​

  • Triggered when the bound value updates.
  • Behavior:
    • If binding.value is truthy and no error message exists:
      • Creates a new error message element.
      • Adds .input-error class to the target inputs.
    • If binding.value is truthy and error message exists:
      • Updates the error message text.
      • Adds .input-error class to the target inputs.
    • If binding.value is falsy:
      • Removes .input-error class from the target inputs.
      • Removes the error message element.

Usage ​

vue
<template>
  <div class="form-field" v-input-error="errorMessage">
    <label>Username</label>
    <input v-model="username" type="text" placeholder="Enter username" />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";

const username = ref("");
const hasError = computed(() => username.value.length < 3);
const errorMessage = computed(() =>
  hasError.value ? "Username must be at least 3 characters" : "",
);
</script>

Screenshot ​

v-input-error image


Styling ​

The directive applies the following styles/classes:

  • .input-error class to inputs (input and .multiselect__tags) when an error is present.
  • .field-error.error-message classes to the generated error message <span> at the bottom of the container.
  • These target classes apply custom styling (such as red borders) matching the application's design system.

Notes ​

  • Targets <input> as well as .multiselect__tags inside the bound container element to apply error borders.
  • Appends a <span> with the error message at the end of the container.
  • Automatically cleans up error UI when the bound value becomes falsy (e.g., null, '', undefined).
  • Adds .error-message and .field-error classes to help target or style error messages.
  • Best use case is to display errors returned from backend form validation.