P
P
postya2020-06-20 16:30:13
Vue.js
postya, 2020-06-20 16:30:13

How to validate an imported component in Vue Js with vee-validate?

I want to validate textarea on button click. To test: if textarea is empty then show error:
"Field is required"
If not, remove error
How to make vee-validate validation work on imported components in Vue js?

I include vee-validate in the main.js file:

import { ValidationProvider } from "vee-validate";
import * as VeeValidate from "vee-validate";
import { extend } from "vee-validate";
import { required } from "vee-validate/dist/rules";

Vue.use(VeeValidate);
Vue.component("ValidationProvider", ValidationProvider);

extend("required", {
  ...required,
  message: "Field is required!"
});


There is a textarea component in a separate file TextAreaQuestion.vue :

<template>
  <div>
    <textarea
      class="sentence-textarea"
      cols="30"
      rows="3"
      v-model="questionText"
      placeholder="type your question here"
    ></textarea>
  </div>
</template>

<script>
export default {
  name: "TextAreaQuestion",
  data() {
    return {
      questionText: "1111"
    };
  }
};
</script>


In the Admin.vue file, I import this component and use it:
<ValidationProvider name="question" rules="required">
  <div slot-scope="{ errors }">
      <TextAreaQuestion v-model="question" />
    <p v-bind:class="[ hasError ? 'showError' : 'noError']">
    {{ errors[0] }}
    </p>
    </div>
    </ValidationProvider>
<script>
import TextAreaQuestion from "../components/TextAreaQuestion";

export default { {
components: {		
    TextAreaQuestion,		
  },
data() {
    return {
      question: "",			
      hasError: true
    };
  },
}
</script>


If I don't use components, but simple elements, for example:
<ValidationProvider name="question" rules="required">
        <div slot-scope="{ errors }">
          <label for="question">Question</label>
          <input type="text" id="question" v-model="question" />
          <p v-bind:class="[hasError ? 'showError' : 'noError']">
            {{ errors[0] }}
          </p>
        </div>
      </ValidationProvider>


then validation works, but not for components (

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question