Extend vee-validate rules dynamically

2.8k Views Asked by At

I am using vee-validate to validate input fields.

As I need to validate IBAN inputs, I installed ibankit as a dependency and added this to my app.js

import {IBAN} from "ibankit";
import {extend, ValidationProvider} from 'vee-validate';
import Vue from 'vue';

Vue.component ('ValidationProvider', ValidationProvider);

extend ('required', {
    ...required,
    message: 'This field is required'
});

extend ('email', {
    ...email,
    message: 'This field needs to be a valid e-mail adress'
});

extend ('integer', {
    ...integer,
    message: 'This field needs to be an integer'
});

extend ('iban', {
    validate: (str) => {
        return IBAN.isValid (str);
    },
    message: 'This is not a valid IBAN'
});

const main = new Vue ({
    el: '#app',
    store: store,
    render: h => h (App)
});


export default main;

Unfortunately the ibankit-rules are very heavyweight and unused most of the time.

My idea was to include it to a component called IbanInput.vue and extend the rule there:

<template>
    <ValidationProvider :rules="{ iban: true }" :vid="name" v-bind="$attrs" v-slot="{ errors }" tag="div" class="w-full">
        <input
           [...]
        >
    </ValidationProvider>
</template>
<script>
export default {
    name: 'IbanField',
}
</script>

Now I am wondering, how I can import ibankit and extend vee-validate-rules here. Maybe it's even possible to prevent the rule to be added twice, if the iban-field is included twice...?

1

There are 1 best solutions below

0
On BEST ANSWER

You have two ways here, you could load the ibankit itself asynchronously and extend it with dynamic import():

import('ibankit').then(module => {
  extend('iban', ...);
});

The second option is to use async components which is what I would prefer as it is much simpler.

Import your ibankit into your component and call extend as you would normally anywhere before your export statement or inside a lifecycle hook.

Then define your IbanInput as an async component:

{
  components: {
    IbanInput: () => import('@/components/IbanInput.vue')
  }
}

Either way, you don't have to worry about importing it multiple times as the browser would've already loaded the bundle and vee-validate will just overwrite it, so no issues there.