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:
    • Adds .border-red-500 class to the <input> inside el.
    • Adds .border-red-500 class to the container element.
    • Appends an error <span> with classes text-red-500, text-[12px], 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 .border-red-500 class to the input.
    • If binding.value is truthy and error message exists:
      • Adds .input-error class to the container.
      • Adds .border-red-500 class to the input.
      • Updates the error message text.
    • If binding.value is falsy:
      • Removes .input-error class from the container.
      • Removes .border-red-500 class from the container and input.
      • Removes the error message element.

Usage

vue
<template>
    <main>
        <div v-input-error="errorMessage">
            <input type="text" v-model="name" placeholder="Enter your name" />
        </div>
    </main>
</template>

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

const name = ref("");
const errorMessage = ref("This field is required");

watch(name, (newVal) => {
    errorMessage.value = newVal.trim() === "" ? "This field is required" : "";
});
</script>

Screenshot

v-input-error image


Styling

The directive applies these Tailwind CSS classes:

  • .flex & .flex-col to the the element to align properly
  • .border-red-500 to both the container and input elements when an error is present
  • .text-red-500 and .text-[12px] to the error message
  • .input-error to the container element when updating with an error

Notes

  • Looks for an input inside the bound element to apply border styling.
  • Appends a <span> with the error message at the end of the container.
  • Automatically cleans up error UI when value becomes falsy (e.g., null, '', undefined).
  • Adds .error-message class to help target or style error messages.
  • Best use case is to return errors that the backend validation sends.