Misone
Misone

Reputation: 33

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

Upvotes: 1

Views: 3852

Answers (2)

zcoop98
zcoop98

Reputation: 3089

Two ways: (Per the VeeValidate3 docs)

You can change the error message by returning strings in the validation function itself:

import { extend } from 'vee-validate';

extend('positive', value => {
    if (value >= 0) {
        return true;
    }

    return 'This field must be a positive number';
});

Or, you can use the extended format and pass in a message property:

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;
    },
    // message property:
    message: 'The date format is incorrect',
});
validators.push('dateFormat');

Localization

The aforementioned solutions fall short if you're looking to support multiple languages.

Based on the docs, you should be able to add localized messages for any language using the { localize } import and the following object syntax:

import { localize } from 'vee-validate';

localize({
  en: {
    messages: {
      required: 'this field is required',
      min: 'this field must have no less than {length} characters',
      max: (_, { length }) => `this field must have no more than ${length} characters`
    }
  }
});

As a sidenote, you can also simplify your if (reg.exec(value) === null) ... lines to:

return reg.exec(value) !== null;

Upvotes: 1

Misone
Misone

Reputation: 33

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' });

Upvotes: 0

Related Questions