Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With VeeValidate, how can I see if a field has been touched and is valid?

I'm trying to access the validation flags from a computed prop:

computed: {
  isFormValid() {
    let isValid = this.$validator.fields.some(field => {
      console.log(field.flags);
      return field.flags.touched; || field.flags.invalid;
    });
    console.log("isValid", isValid);
    return isValid;
  }
},

But this gives an error: "TypeError: this.$validator.fields.some is not a function"

So then I figured I would iterate over the observable:

let isValid = Array.from(this.$validator.fields).some(field => {
  console.log(field.flags);
  return field.flags.touched; //|| field.flags.invalid;
});

Yay! Progress! No more error. But it doesn't recompute when I change the form input values.

So how can I do this?

like image 941
Shamoon Avatar asked Oct 18 '25 09:10

Shamoon


1 Answers

The v2 docs show an example that iterates this.fields (instead of this.$validator.fields) via Object.keys:

// MyComponent.vue
export default {
  // ...
  computed: {
    isFormDirty() {
      return Object.keys(this.fields).some(key => this.fields[key].dirty);
    }
  },
  //...
}

Using that example, your computed prop would be:

// MyComponent.vue
export default {
  // ...
  computed: {
    isFormTouchedOrInvalid() {
      return Object.keys(this.fields).some(key => this.fields[key].touched || this.fields[key].invalid);
    }
  },
  //...
}

v2 demo

In v3, you could use the <ValidationProvider> component to easily access the validation flags in the template:

<ValidationProvider rules="required" v-slot="{ touched, invalid }">
  <pre>touched:{{touched}} invalid:{{invalid}}</pre>
  <input type="email" v-model="value">
</ValidationProvider>

v3 demo

like image 83
tony19 Avatar answered Oct 19 '25 22:10

tony19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!