What is the best way to retrieve the errors recorded property from a customized input component that has been validated with vee-validate?

I am currently exploring the use of VeeValidate within a custom input component.

In my attempts, I have experimented with using $emit on both @input and @blur events. However, I have encountered an issue where validation takes place in the next tick, causing me to miss capturing the validation event.

  onEvent (event) {
    console.log('error length', this.errors.items.length)
    if (this.errors.items.length) {
      this.hasError = true
      this.$emit('has-error',this.errors.items)
    } else {
      this.hasError = false
      this.$emit('on-input', event)

    }
  }

I also tried injecting the validator from the parent component to directly access the errors computed property. However, due to multiple levels of nesting between the parent page and the custom input component, this approach led to complications. The components are designed for reusability, so injecting the validator through all layers is not ideal.

 export default {
   //in custom input component
   inject: ['$validator'],
 }

The most promising solution I came up with involves watching the changes in the errors computed property and emitting an event when a change occurs with the errors specific to that instance of the component.

watch: {
  errors: function (errorsNew) {
    console.log('errors watch',errorsNew)
  }
},

However, I faced difficulties in watching the errors computed property introduced by vee-validate.

Here is a simplified version of the code:

Parent Component:

<template>
  <div id="app">

    <CustomInput
      :label="'Label1'"
      :value="'value from store'"
      :validations="'required|max:10|min:5'"
      :name="'label1'"
    />
    <button>Save</button>
  </div>
</template>

<script>
import CustomInput from "./components/CustomInput";

export default {
  name: "App",
  components: { CustomInput }
};
</script>

Custom Input Component:

<template>
   <div>
     <label >{{ label }}</label>
     <input :value="value" :name="name" v-validate="validations">
     <span v-if="this.errors.items.length">{{this.errors.items[0].msg}}</span>
  </div>

</template>

<script>
export default {
  name: "HelloWorld",

  props: {
    label: {
      type: String,
      required: true
    },
    value: {
      type: String,
      default: ""
    },
    validations: {
      type: String,
      default: ""
    },
    name: {
      type: String,
      required: true
    }
  },

  watch: {
    errors: function(errorsNew) {
      console.log("errors watch", errorsNew);
      this.$emit('has-error')
    }
  }
};
</script>

If anyone can assist me in accessing the validation errors from the custom input component, I would greatly appreciate it.

Update:

I have created a simple fiddle for easier testing: https://codesandbox.io/s/mqj9y72xx

Answer №1

To effectively handle this issue, it would be most beneficial to inject $validator into the child component, as suggested by the plugin's recommendations found here: .

In your CustomInput component, simply include inject: ['$validator'].

Then, within App.vue, you can implement the following in the template:

<div>
  These errors pertain to "label1" in App.vue:
     <span v-if="errors.has('label1')">{{errors.first('label1')}}</span>
</div>

That should cover everything.

You can refer to this working example based on your initial scenario: https://codesandbox.io/s/pw2334xl17

While I understand that you've already explored this option, it's worth noting that the inject method climbs up the component hierarchy to locate a $validator instance. To ensure consistency across components seeking to inject a validator, consider disabling automatic injection globally in your app at the root level using:

Vue.use(VeeValidate, { inject: false });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What specific types of errors is this try-catch block designed to catch and manage?

// This function establishes a connection to MongoDB using Mongoose const connectToDatabase = (url) => { return mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('Conn ...

Tips on toggling the visibility of div elements with JavaScript

In my selection block, I have three categories of elements and associated Divs. The goal is to display the related divs when a category is selected, while keeping them hidden otherwise. Specifically, I want the husband_name and number_pregnancy divs to be ...

Hidden overflow and identification in URL causes content to be invisible and suddenly appear at the top of the page

I'm encountering a strange issue with containers that have overflow:hidden and when the page URL includes an id. The content gets pushed up and becomes invisible. This problem arises when I apply padding and negative margin at the bottom to create equ ...

Mastering the management of various events within React Material UI components

I am working with a Material UI Switch Component and need to detect click events on it. In certain situations, I want to prevent the change event from triggering. What is the most effective way to achieve this? While I have previously used event.preventD ...

tracking scroll position within div on main page

I have a div tag enclosed within a content tag due to the implementation of a masterpage containing the forms and body tags. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"> <div id="xxx" style="overflow:s ...

Create individual account pages with specific URLs in Next.js

I'm currently working on developing a website that will feature individual user pages showcasing their posts and additional information. I'm facing some difficulty in figuring out how to generate new links to access these user accounts. For insta ...

Breaking the layout using recursive components in VueJS

I am currently facing an issue where I need to dynamically load components. However, when some of these components are loaded, they appear with faulty or missing CSS styles due to a problematic first div element after the template. Removing this DIV manual ...

JS - What is causing my JavaScript src to not work properly?

Here is a snippet of my code: <form name="calculator"> <input type="button" name="latest" value="You are not using the latest version."> <script src="http://www.alvinneo.com/bulbuleatsfood.js"> if(latest-version==="1.0.4.2"){ document.ca ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

Playing audio from local blob data is not supported on mobile browsers

I'm trying to stream blob data in mp3 format, but I'm experiencing difficulties with mobile browsers. The code below works perfectly on PC browsers, but not on mobile: // Javascript var url = URL.createObjectURL(blob); audio = document.getEleme ...

Having trouble assigning more than one custom named property in TypeScript for MUI v5 Palette

I am currently setting up multiple custom attributes to make future updates easier. Nonetheless, I'm encountering a challenge with implementing more than one custom property in MUI v5. TypeScript Error TS2717: Subsequent property declarations must hav ...

Setting up the karma ng-html2js preprocessor to locate my templates within a specific folder

Currently, I am facing an issue where I need to set the templateUrl: "partials/my-directive.html" However, I find that I have to use templateUrl: "app/partials/my-directive.html for it to be loaded by Karma. This is how my folder structure looks like (fo ...

The data type 'string' cannot be assigned to the type '(url: string) => string'.ts(2322)

I am working with a Material UI copyright component: export default function Copyright(link: string, text: string) { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link co ...

Submit a POST request using CoffeeScript to get a string from the returned object

I am encountering a small issue. Whenever I execute myVar = $.post('/check_2/', JSON.stringify({"newname": window.NEWNAME,}), callback, 'json') The variable 'myVar' holds an object. When I use console.log myVar, the output i ...

Experiencing issues with regex in JavaScript: all text enclosed within <angular> brackets vanishes

I am trying to analyze a formula and present it on the screen. For instance, I want to be able to input <path>T Q, where <path>T remains unchanged, and Q is a variable. It accepts this input, but when displaying it on the screen, only T Q shows ...

Can you provide me the steps to delete the title attribute from images in Wordpress?

My client has expressed dissatisfaction with the tooltip that appears when hovering over images in certain browsers, particularly Safari. This tooltip displays the title attribute within the img tag, which is a requirement enforced by Wordpress. Even if w ...

Maximizing PUT Methods in HTTP RESTful Services

I've been playing around with my routes file and I'm looking to switch up the method being called (delete instead of update). Code Snippets: # User management API GET /users @controllers.Users.findUsers POST /user ...

Problem with AngularJS Multiselect checkbox dropdown configuration

In my application, I have a pop-up that includes a multi-select dropdown menu. Here is the code for the Multi-Select Dropdown: <select name="edit_tags" class="form-control" id="advisor_article_tagsx" multiple="" required ng-model="article_selected ...

Learn the best way to send query parameters through the Next.js navigation router and take advantage of

Currently, I am implementing import { useHistory } from 'react-router-dom' const history = useHistory() ... history.push('/foo?bar=10') However, only the 'foo' part is being pushed into the url. What is the correct way to pas ...

In case the desired property is not detected in the object, opt for an alternative property

Here is an example object: Object -> Content: <h1>some html</h1> Url : A url In the code below, I am checking if a specific URL exists in the given object: var checkURLInArray = function(url, array) { for(var i in array) { ...