Search code examples
validationvue.jsvuelidate

Vuelidate, can I inherit a custom method via mixin?


Using Veulidate, using VueJS 2 on a project built using Vue CLI, I'm simply trying to using a custom method for the purpose of validating a phone number. The method is coming from a global mixin located in main.js.

main.js

Vue.mixin({
  methods: {
    vd_phone(val) {
      var phonePattern = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
      return phonePattern.test(val) ? true : false
  }
});

form.vue

validations: {
  phone: {
    required,
    phone: this.vd_phone
  }
}

Seems simple enough, right? Over and over, I get Cannot read property of 'vd_phone' of undefined. Tried vd_phone, this.vd_phone, this.vd_phone(), etc..

Also tried putting the method into a global methods option (instead of a mixin) and trying to access it via $root like this:

main.js

var vm = new Vue({
  router, el: '#app', store,
  methods: {
    vd_phone() {
      var phonePattern = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
      return phonePattern.test(val) ? true : false;
    }
  },
  render: h => h(App)
});

Same problem! In my form.vue file I attempted accessing this method using this.$root.vd_phone, $root.vd_phone, etc.. no dice.

This is all I found on the topic: https://github.com/vuelidate/vuelidate/issues/308, but this seems to talk about inheriting entire validator properties - not just a method.

Any help is appreciated.


Solution

  • You're using a factory pattern to instantiate a function from it's source for use in other files. To do this you must export from the source file so other files can import it, like this:

    main.js

    export default {
          vd_phone(val) {
             var phonePattern = /^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/;
             return phonePattern.test(val) ? true : false;
       }
    }
    

    Then import the file where ever you need that function, and you will have access to it.