Search code examples
vue.jsblurvuelidate

How to validate only onblur with Vuelidate?


From my parent component I'm calling my custom input child component this way:

<custom-input
  v-model="$v.form.userName.$model"
  :v="$v.form.userName"
  type="text"
/>

And here's my custom input component:

<template>
  <input
    v-bind="$attrs"
    :value="value"
    v-on="inputListeners"
    :class="{ error: v && v.$error }"
  >
</template>

<script>
export default {
  inheritAttrs: false,
  props: {
    value: {
      type: String,
      default: ''
    },
    v: {
      type: Object,
      default: null
    }
  },
  computed: {
    inputListeners () {
      const vm = this
      return Object.assign({},
        this.$listeners,
        {
          input (event) {
            vm.$emit('blur', event.target.value)
          }
        }
      )
    }
  }
}
</script>

This triggers validation errors from the very first character entered in the input field (which is arguably poor UX, so I really don't understand why this is default behavior).

Anyway, how to trigger such errors only on blur event?


Solution

  • Try to emit the input event from the handler of blur event so :

    instead of :

    v-on="inputListeners"
    

    set

    @blur="$emit('input', $event.target.value)"