Ensuring child input components are validated upon submission using Vee-Validate and Vue.js 2

Currently, I am working on creating a Registration form with multiple "Input Field" components that require validation once the Submit button is pressed. While each input field validates individually when the text is changed, I am struggling to implement a global call to validate all input fields at once. My goal is to achieve something similar to the example here:

This issue is akin to the question posted here: Validate child input components on submit with Vee-Validate, but I am having trouble grasping the solution.

Here is my 'singleInput.vue' component:

<template lang="html">
  <div :class="'col m'+col">
    <div class="input-field">
      <i v-if="icon" class="material-icons prefix">{{icon}}</i>
      <input
      v-if="area"
      :type="type"
      @input="onChange"
      :id="id"
      :required="required"
      :name="id"
      v-validate="'required'"
      />
      <textarea
      v-if="!area"
      @input="onChange"
      :id="id"
      :required="required"
      :name="id"
      class="materialize-textarea"></textarea>
      <label :for="id">
        {{label}}
        <span v-if="required" class="red-text">*</span>

      </label>
      <span class="red-text error">{{$store.state.errors[id]}}</span>
    </div>
  </div>
</template>

<script>

export default {
  name:'single-input',
  props: {
    col:{
      type: Number,
      default:6
    },
    id:{
      type: String,
      required:true
    },
    required:{
      type:Boolean,
      default: true
    },
    label:{
      type:String,
      required:true
    },
    onChange:{
      type:Function,
      required:true
    },
    area:{
      type: Boolean,
      default: true
    },
    type:{
      type: String,
      default: "text"
    },
    icon:{
      type:String
    },
    validation:{
      type:String
    }
  }
}
</script>

<style lang="css">

</style>

And here is the 'Info.vue' component:

<template lang="html">
  <div class="row">
    <single-input v-for="(info,i) in informations" :id="info.id" :label="info.label" :onChange="onChange" :area="info.area" :key="i" :required="info.required" :col="info.col" :type="info.type" :icon="info.icon"></single-input>
  </div>
</template>

<script>
import SingleInput from "./SingleInput";
export default {
  name: 'info',
  methods:{
    onChange(e){

    }
},
  data(){
    return{
      informations:[
        {
          label: "First Name",
          id: "fname",
          icon: "person"
        },
        {
          label: "Last Name",
          id: "lname",
          required:false,
          icon: "person"
        },
        {
          label: "Email",
          id: "email",
          type:"email",
          icon:'email'
        },
        // Add more information objects as needed...
      ]
    }
  },
  components:{
    SingleInput
  }
}
</script>

<style lang="css">
</style>

I have been trying my best, but I am unable to access errors in 'Info.vue'. Any assistance would be greatly appreciated!

Answer №1

I couldn't find any validation attempt in the example you provided, but I have a working example on jsfiddle that you can check out here: link

Here's what I did: - Added a submit method to the info component

submit: function(){
        var validationArray = this.$children.map(function(child){
        return child.$validator.validateAll();
      });

    window.Promise.all(validationArray).then((v) => {
            alert('Form Submitted!');
        }).catch(() => {
            alert('Correct those errors!');
        });
    }

This method essentially validates all children of your info (single-inputs in this case).

- Made a small change to the template for displaying error messages:

{{ ($validator.getErrors().errors.length > 0) ? $validator.getErrors().errors[0].msg : '' }}

Edit: I can only guess what was wrong with your code, but I believe the issue may have been related to accessing direct validators under components with inputs - single-inputs, not the info component.

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

Attempting to transmit information to database using AJAX in the context of CodeIgniter

I'm having some trouble with my AJAX setup. It doesn't seem to be posting any data to the database, despite trying various solutions I found online. That's why I've turned to this platform for help. When testing in Postman and sending ...

Tips for deactivating dropdown values based on the selection of another dropdown

There are two dropdown menus known as minimum and maximum, each containing numbers from 1 to 25. If a value is selected from the minimum dropdown (e.g. 4), the maximum dropdown should only allow values that are equal to or greater than the selected value ...

What is the most effective approach to seamlessly conceal and reveal a button with the assistance

I have two buttons, one for play and one for pause. <td> <?php if($service['ue_status'] == "RUNNING"){ $hideMe = 'd-none'; } ?> <a href="#" class="btn btn-warning ...

What is the process for adding or modifying attributes in child elements?

I have been experimenting with a simple script that adds the target="_blank" attribute to all the <a> elements. $(function(){ $('a').attr('target', '_blank'); }); While it is functioning perfectly, I am now interested ...

What is the reason behind the linking or appearance together of src/pages in Visual Studio Code?

As I venture into the world of Visual Studio Code (VSC) and follow a Gatsby tutorial, I've noticed that every time I create a new directory, VSC seems to automatically link src/pages together. However, my preference is for pages to be a subfolder of s ...

JS Tips for using the .push() function with Multidimensional Arrays in JavaScript

After coming across this code example online, I decided to give it a try. The code snippet involved using the JavaScript array push method to add new elements to an inner sub-array, which was exactly what I needed to achieve! The code successfully demons ...

What is the best way to fix multiple dropdown menus opening simultaneously in Vue.js?

I am working on an application that generates todo lists for tasks. These lists can be edited and deleted. I am trying to implement a dropdown menu in each list to provide options for updating or deleting the list individually. However, when I click on the ...

A step-by-step guide to displaying image upload previews using React

I am currently working on developing an image upload form with the use of Next.js/React.js. The goal is to allow users to assign tags to each uploaded image and display a preview of the image using 'URL.createObjectURL'. Although the uploading pr ...

Searching through data fields in MongoDB that have been filled with information

In my Mongoose queries, I am dealing with models known as "Activities" that have a specific schema structure. This schema includes fields such as actor, recipient, timestamp, activity, event, and comment. var activitySchema = new mongoose.Schema({ act ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Is there a way to streamline and optimize this React/Material UI code for faster performance?

There seems to be a lot of repetition in the code that needs to be cleaned up. I'm wondering if the switch statement is necessary. It looks like it requires the muiTheme palette to be passed this way. Also, can these theme constants be placed in a sep ...

I have discovered some amazing jQuery image hover effects that are simply breathtaking –

I have been using the Adipoli jQuery Image Hover Effects plugin, but I am facing issues with changing certain properties. The image is set to change to grayscale initially and then switch to color on hover. However, when I click on the image, it should mai ...

Making a Jquery 1.10.2 cross-domain request

I am in need of assistance with the following code snippet: function doPoolPartyGetChildrenAjaxRequest(parent) { return $.ajax({ url: "http://127.0.0.1:8086/PoolParty/api/thesaurus/1DCE2E49-7DD8-0001-524C-1A1B14A0141A/childconcepts", data: {lan ...

Using the power of HTML5, store data locally on

I am curious about the possibility of using local storage on a different page. I want to track clicks made on one page and display it on another, but I'm not sure how to go about it or if it's even feasible. Any help you can provide would be grea ...

Is there a way for me to manage the appearance of the printed document's layout?

I have successfully added 3 print buttons to my website, each one designed to print a specific portion (div) of the webpage. Here is the code snippet for this functionality: function printPage(id) { var html="<html>"; //html+="<link rel="st ...

Checking for any lint errors in all JavaScript files within the project package using JSHint

Currently, I am utilizing the gulp task runner to streamline my workflow. My goal is to implement JsHint for static code analysis. However, I have encountered a setback where I can only run one file at a time. Upon npm installation, "gulp-jshint": "~1.11. ...

Retrieving a variable value set within a jQuery function from within an Angular 2 component

In the current project, I am facing a situation where I need to work around and initialize jQuery datetimepicker inside an Angular 2 application (with plans to refactor it later). However, when I assign a datetime value to a variable, I encounter a proble ...

The JS script is activated only when the window is resized

I have incorporated a touch image slide using an external library called SwipeJS. However, it seems to only function properly when I resize my browser window. Within the body, I have structured my images in the Swipe Container as follows: <div id=&apo ...

Guide on importing CDN Vue into a vanilla Typescript file without using Vue CLI?

In the midst of a large project that is mostly developed, I find myself needing to integrate Vue.js for specific small sections of the application. To achieve this, I have opted to import Vue.js using a CDN version and a <script> </script> tag ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...