4

I have a button, for load files or add some text
After load it pushed in data() prop
How i can validate this prop, if them not have input

Im found only one solution - make watch for data props. and set validate in
Maybe exist more beautiful way?

I try validator.verify() - but it dont send error in main errorBag from validateAll

This is example

<div id="app">
  <testc></testc>
</div>

<script type="text/x-template" id="test">
<div>
    <input type="text" v-validate="'required'" name="test_vee">
   {{errors.first('test_vee')}}
  <hr>
    <button @click="addRow">Add</button>
    <input type="text" v-model="inputValue" name="test_input"/>
  <hr>
    {{rows}}
  <hr>
  {{errors.first('rows')}}
    <button @click="validateForm">Validate</button>
  </div>
</script>

and script

Vue.component('testc', {
  template: '#test',
  data() {
        return {
            inputValue: '',
            rows: []
        }
    },
  watch: {
    rows: {
      handler: function(newVal, oldVal) {
        this.$validator.errors.remove('rows');
        if (this.rows.length < 2) {
          this.$validator.errors.add({
            id: 'rows',
            field: 'rows',
            msg: 'Need 2 rows!',
          });
        }
      }
    }
  },
  methods: {
    addRow: function() {
      this.rows.push(this.inputValue);
      this.inputValue = '';
    },
    validateForm: function(){
       this.$validator.validateAll();
    }
  }
});

Vue.use(VeeValidate);

new Vue({
  el: '#app'
})

https://codepen.io/gelid/pen/YBajER

First input in example: default validate - its ok
Second input: for add items - dont need validate or has self validate (not empty for example)
In data of component i have prop rows - it is need validate before ajax request to backend for save data

Sliva
  • 63
  • 6

1 Answers1

0

This is what worked for me when I needed initial input to be validated and show a message prior to any user interaction (using Vue 3 composition API):

const { setFieldError, setFieldValue, values } = useForm<IFormValues>({
....
})

if (isCreating) {
    setFieldValue("name", "");
    setFieldError("name", "A name is required");
}

Hopefully, this may provide some ideas as to how to resolve this issue.

SteveC
  • 644
  • 7
  • 12