Is it possible to validate multiple fields within a Vue component by integrating other components and utilizing Vee-Validate for a comprehensive validation process?

Currently, I am utilizing Vue.js version 2.5.13 along with Vee-Validate version 2.0.3. Here is the structure of my code:

./component-one.vue:

<template>
  <div>

    <input type="text" name="input_one" id="input_one"
           v-model="input_one" 
           v-validate="'required'"
           :class="{'is-danger': errors.has('input_one')}" />

    <component-two></component-two>

    <button @click="submitForm">Submit!</button>

  </div>
</template>

<script>
  import Vue from 'vue'
  import VeeValidate from 'vee-validate'
  import ComponentTwo from './component-two.vue'

  Vue.use(VeeValidate, {
    events: 'input|blur'
  })

  export default {
    name: "component-one",
    components: {
      ComponentTwo
    },
    data() {
      return {
        input_one: '',
      }
    },
    methods: {
      submitForm: function () {
        this.$validator.validateAll().then((result) => {
          if (result) {
            alert('From Submitted!')
            return
          }
          alert('Correct them errors!')
        })
      }
    }
  }
</script>

./component-two.vue:

<template>
  <div>

    <input type="text" name="input_two" id="input_two"
           v-model="input_two" 
           v-validate="'required'"
           :class="{'is-danger': errors.has('input_two')}" />

  </div>
</template>

<script>
  export default {
    name: "component-two",
    data() {
      return {
        input_two: ''
      }
    }
  }
</script>

I am seeking a way to validate a field within ComponentTwo when the @click event occurs on the button in ComponentOne (in order to save all form data within this component).

Given that I have a large form composed of similar small Vue-components (all encapsulated within ComponentOne), it would be ideal to validate all of them in one centralized location.

Answer №1

To manually trigger the validateAll() function on a component in Vue, you can do so by referencing the Vue instance:

Parent Component Example

<template>
  <div>

    <input type="text" name="input_one" id="input_one"
           v-model="input_one" 
           v-validate="'required'"
           :class="{'is-danger': errors.has('input_one')}" />

    <component-two ref="validateMe"></component-two>

    <button @click="submitForm">Submit!</button>

  </div>
</template>

<script>
  import Vue from 'vue'
  import VeeValidate from 'vee-validate'
  import ComponentTwo from './component-two.vue'

  Vue.use(VeeValidate, {
    events: 'input|blur'
  })

  export default {
    name: "component-one",
    components: {
      ComponentTwo
    },
    data() {
      return {
        input_one: '',
      }
    },
    methods: {
      submitForm: async function () {
        // Validate before submitting form
        const result = await this.$validator.validateAll() && await this.$refs.validateMe.$validator.validateAll()
        if (result) {
          alert('Form Submitted!')
          return
        }
        alert('Please correct the errors!')
      }
    }
  }
</script>

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

Limit the selected values to calculate a partial sum

Imagine two distinct classes called professor and student: professor.ts export class Professor { id: number name: string } student.ts import { Professor } from "./professor" export class Student { ...

Open the window by using the `Window.open` method, then find and

Is there a way to open a document, not in a new window but on the same page using JavaScript.Window.Open()? Could it be possible to display the document within a specific div element that is obtained with getElementById? For example: document.getElementB ...

Jade iterates over each object element, assigning its children to their respective parent elements

I have a JavaScript Object named "boards". [{"id":1,"parent_board":0,"title":"Lorem 1","description":"ec40db959345153a9912"}, {"id":2,"parent_board":0,"title":"Lorem 2","description":"bb698136a211ebb1dfedb"}, {"id":3,"parent_board":1,"title":"Lorem 1-1"," ...

A step-by-step guide on recompiling Vue using shell_exec()

I am facing an issue with my Vue application that is supposed to receive updates via webhook.php. In this setup, there is a PHP script responsible for updating internal configurations. The problem arises at the end of the webhook.php file where I have incl ...

Lazy loading in Vue3 using vue-i18n is a powerful feature to

I'm interested in implementing lazy loading for individual languages in my APP, but I'm having trouble understanding the example provided. Here is the example: i18n.js import { nextTick } from 'vue' import { createI18n } from 'vue ...

In order to ensure proper alignment, adjust the width of the select element to match the width of the

Is there a way for the select element to adjust its width based on the length of the selected option? I want the default option value's width to be shorter, but once another option is selected, I'd like the select element to resize itself so that ...

The Web Browser is organizing CSS elements in an alphabetized sequence

map.css({ 'zoom': zoom, 'left': map.width()/(2*zoom) - (point[0]/100)*map.width(), 'top': map.height()/(2*zoom) - (point[1]/100)*map.height() Upon observation, it appears that Chrome adjusts the map zoom first be ...

Retrieving information from Node.js Serialport

I am interested in reading the data received after sending an ascii command to my lock controller. Here is the code that sends the command to the lock controller: var express = require('express'); var router = express.Router(); var SerialPort = ...

Execute a bash script from a local URL using fetch

I'm curious about converting a curl command into a bash script with input variables using fetch. It works perfectly in the console: curl -s http://localhost:3001/ident.sh | bash /dev/stdin x627306090abab3a6e1400e9345bc60c78a8bef57 2 10194897676576 ...

Changing a string to uppercase and lowercase

I am currently working on a software that takes a string, divides it, capitalizes the first letter of the first string, and capitalizes all letters in the second string. Below is the code snippet: var fullName = "ThEoDORe RoOseVElT"; function nameEditor( ...

After the page has finished loading, the JavaScript code is not able to

I have created a dynamic jobs list from a database that includes conditional salary reporting based on union type. I decided to build the dataset in the page load section of the CS page for output to a label on the ASPX page to handle the conditional state ...

Determining validity of a form field in vue.js

I've been working on a Vue application and I'm currently dealing with identifying the invalid state of a form field. Simply put, I want to be able to determine if a field is in an invalid state, such as when it's required but left empty upon ...

Tips for removing JavaScript functions that were initialized after an ajax request

In my setup, there are two main pages: Page A and Page B. Page A consists of the following components: HTML for Page A JavaScript for Page A JavaScript for Page B Subsequently, I utilize an ajax call to inject Page B's HTML into Page A and trigger ...

Combining the total of numerous inputs that are multiplied by a specific value all at once

Hey, I've been working on a project with a table and an input field with costs using jQuery. You can check out This Fiddle for reference. $( ".total" ).change(function() { let i = 1; var input001 = document.getElementsByName(i)[0]; var ...

Ways to activate javascript following a PHP submission?

It's a bit tricky to explain. function m(val){ var element=document.getElementById('othermethod'); if(val=='others') element.style.display='block'; else element.style.display=&apo ...

Modify the divs in two separate occasions when submitting different forms

Within my form, I have radio buttons located inside div1, a captcha code to be solved in div2, and additional content in div3. My goal is to have div1 replaced by div2 when a radio button is checked and submitted. Then, after completing the captcha in div2 ...

What is the method to access and examine the attributes of a range in Office.js?

I am encountering an issue while attempting to retrieve the values from cell B2 and create a conditional statement based on those values. Despite my efforts, I continue to receive an error message without any clear understanding of its cause. Please refe ...

Identify user input with Python Selenium for keyboard and mouse interactions

As a frequent user of Selenium Browser for my everyday browsing needs, I am looking to implement some code that will be triggered when certain keys are pressed on any page. Initially, I considered loading JavaScript onto each page to track key and mouse in ...

Utilizing a refreshed array of elements within a component directive

When working within a view, I am utilizing ng-repeat inside a directive to iterate over an array of objects from my controller. However, as the objects in the array undergo value changes, I encounter a dilemma when transitioning to a new instance of the sa ...

How can a JavaScript function be assigned as a parameter to be used in conjunction with another function?

Currently, I am delving into the realm of JavaScript and there is one concept that has me a bit puzzled - passing functions as parameters to other functions. I grasp the idea in theory, but I am struggling to see its practical application. So, my query is ...