search

Home  >  Q&A  >  body text

How to use validation function of child component in vue js 2 to validate input in parent component?

I try to create reusable components in my vue project. This is part of the training I am receiving. But I think my code needs some help, it's confusing me.

let validations = {}

validations.firstName = function(e, that) {
  if (e.target.value == "") that.errors = {
    [that.labelID]: 'Please enter your first name'
  }
  else return true
  that.input_error = !that.input_error
}

validations.phone = function(e, that) {
  if (e.target.value == "") that.errors = {
    [that.labelID]: 'Please enter phone number'
  }
  else if (e.target.value.length > 10) that.errors = {
    [that.labelID]: 'Phone number should be 10 digits only'
  }
  else return true
  that.input_error = !that.input_error
}

validations.email = function(e, that) {
  if (e.target.value == "") that.errors = {
    [that.labelID]: 'Please enter email'
  }
  else return true
  that.input_error = !that.input_error
}

Vue.component('childInput', {
  template: '#my-child-input',
  data() {
    return {
      errors: {},
      input_error: false
    }
  },
  props: {
    labelID: String,
    label: String,
    inputType: {
      type: String,
      default: 'text'
    },
    value: {
      type: [String, Boolean, Number],
      default: null
    },
  },
  methods: {
    handleInput(e) {
      this.$emit("input", e.target.value)
    },
    handleFocusIn(e) {
      this.errors = {[this.labelID]: ''}
      if (this.input_error) this.input_error = !this.input_error
    },
    handleFocusOut(e) {
      switch (this.labelID) {
        case 'firstName':
        case 'phone':
        case 'email':
          validations[this.labelID](e, this)
          break;
        default:
          console.log('in default last name')
          break;
      }
    }
  }
});

new Vue({
  el: '#app',
  data() {
    return {
      event: {
        firstName: '',
        phone: '',
        email: ''
      }
    };
  },
  methods: {
    handleSubmit(e) {
      // I can access firstName, phone and email. 
      // But how to access the validation functions written in child component
      console.log('All data: ', this.event)
    }
  }
})
.someStyleClass {
  margin-bottom: 20px;
}

.input_error {
  border-color: red !important;
  color: red;
}

.labelStyle {
  display: block;
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>

<!-- Parent Component -->
<div id="app">
  <div class="someStyleClass">
    <child-input v-model="event.firstName" label="First Name" label-i-d="firstName" />
  </div>
  <div class="someStyleClass">
    <child-input v-model="event.phone" label="Phone" label-i-d="phone" />
  </div>
  <div class="someStyleClass">
    <child-input v-model="event.email" label="* Email" label-i-d="email" input-type="email" />
  </div>

  <button type="submit" v-on:click="handleSubmit">Validate & Submit</button>

</div>


<!-- Child Component -->
<template id="my-child-input">
  <div>
    <label class="labelStyle" :class="{input_error}">{{ label }}</label>
    <input :class="{input_error}" :value="value" :type="[inputType]" v-on:input="handleInput" v-on:focusout="handleFocusOut" v-on:focusin="handleFocusIn"/>
    <div v-if="errors[labelID]" :class="{input_error}">{{errors[labelID]}}</div>
  </div>
</template>

I am able to validate the input field at the child level and display its related errors near the input field when the focus event occurs. I can also access name, phone and email in the parent component. But when I submit the button from parent, I can't validate the fields. Since the validation is done at the sub-level, so are the errors.

How to check verification and make sure name, phone and email are valid after clicking the button.

renew Every time a user enters incorrect data in an input field, the data is validated individually at the child level. But I didn't find a way to find the same content in the parent component. Because my parent component's data variables are updated at the same time as input.

How to verify at the parent level after clicking submit, without quoting and without using other libraries?

P粉605385621P粉605385621241 days ago390

reply all(1)I'll reply

  • P粉530519234

    P粉5305192342024-03-28 18:18:09

    Maybe what you need is ref to access subcomponents, here is the official documentation: https://v2.vuejs.org/v2/api/#ref

    For the example in question, citation usage is:

    
    
    
    sssccc
    

    reply
    0
  • Cancelreply