Search code examples
javascriptvue.jsvalidationvee-validatevuejs3

Adding a custom error message in VeeValidate3 and VueJS


I'm trying to add a new error message for a custom validator. First, i changed the default language for validation errors this way:

import VeeValidate, { Validator } from 'vee-validate';
import it from 'vee-validate/dist/locale/it';


Validator.localize({ it: it });
Vue.use(VeeValidate, { inject: false, fastExit: false, locale: 'it' });

Here's the extended validator (in another file):

this.$validator.extend('dateFormat', {
                    validate: value => {
                        let reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9][0-9]/;
                    
                    if (reg.exec(value) === null) {
                        return false;
                    }
                    return true;
                }
            });
            validators.push('dateFormat');

How can i show a custom message when the date format is not correct? Thanks


Solution

  • This is how I solved it, do not know if it is the best practice but seems to work:

    //Add this line
    it.messages.dateFormat = function (field) { return 'Format for ' + field + ' not valid'; };
    Validator.localize({ it: it });
    Vue.use(VeeValidate, { inject: false, fastExit: false, locale: 'it' });