how can i clear validation errors when using an onblur trigger?

I don’t think there is any way to prevent Vuetify’s validate-on-blur from running first. So here is how you can do a sneaky workaround without it. Your template will look like this:

<template>
  <v-text-field
    :rules="rules"
    @blur="validate"
    @keydown.enter="validate"
    @focus="clearRules"
    @input="clearRules"
    v-model="localValue"
  />
</template>

Since you won’t use validate-on-blur, you need to manually code the setting and clearing of rules, otherwise they’ll be applied immediately on input. Define a data property with an empty array:

data() {
  return {
    rules: []
  }
},

The rules will be cleared every time the field is focused or input occurs. All that’s needed now is to run a validate method on every blur/keydown which will: 1) set the rules, and 2) compute the result:

validate() {
  this.setRules();
  this.compute();
},
setRules() {
  this.rules = [v => /^([0-9]*[.])?[0-9]+$/.test(v) || "Must be numeric."];
},
compute() {
  try {
    const result = math.evaluate(this.localValue)
    this.$emit("input", result)
  } catch(e) {
    console.log("compute error", e)
  }
},

Here is the working demo (I used eval instead of your mathjs library):

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      // ...
      rules: []
    }
  },
  methods: {
    validate() {
      this.setRules();
      this.compute();
    },
    setRules() {
      this.rules = [v => /^([0-9]*[.])?[0-9]+$/.test(v) || "Must be numeric."];
    },
    compute() {
      try {
        this.localValue = eval(this.localValue);
      } catch(e) {
        // console.log("compute error", e)
      }
    },
    clearRules() {
      this.rules = [];
    }
  }
})
<div id="app">
  <v-app>
    <v-text-field
      :rules="rules"
      @blur="validate"
      @keydown.enter="validate"
      @focus="clearRules"
      @input="clearRules"
      v-model="localValue"
      ></v-text-field>
  </v-app>
</div>



<!-- LIBRARIES -->
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>

Idea taken from here and tailored to work with blur.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top