Search code examples
javascriptvue.jsvuejs2vee-validate

How to customize "required" error messages using a dictionary on VeeValidate (Vue.Js)


I would like to change the error message when an input with "cpf" rule isn't filled (in other words, when an input with "cpf"rule didn't satisfy the "required" rule).

I think that the "dictionary method" with custom messages should do the work, but I couldn't make it work.

With the code below, the error message displayed is just the default pt_br message for "required" fields. I would like to display the message in the dictionary dict below ("Favor preencher o cpf")

In my main.js, I have the following code:

import Vue from 'vue';
import App from './App.vue';
import './core/extensions';

new Vue({
  render: h => h(App),
}).$mount('#app');

And on extensions.js:

 import Vue from 'vue';
 import VeeValidate, { Validator } from 'vee-validate';
 import ptBR from 'vee-validate/dist/locale/pt_BR';

 const dict = {
     messages: ptBR.messages,
     pt_BR: {
      custom: {
         cpf: {
           required: 'Favor preencher o cpf',
         },
       }
     },
   };

Vue.use(VeeValidate);

Validator.localize({ pt_BR: dict })

Validator.extend('cpf', (val) => {
     return false //just to test
});

App.vue (simple example):

<template>
    <div id="app">
        <input type="text" v-validate="required|cpf">      
    </div>
</template>

I'm using vee-validate 2.1.5 and vue 2.5.17


Solution

  • I believe the validator is using cpf as a field name rather than a validation rule in this case.

    I'm not clear on why the cpf rule should trigger the required rule, but if you give the input a name or data-vv-name attribute like:

    <input type="text" data-vv-name="cpf" v-validate="required">
    

    and pass the following arguments to localize:

    Validator.localize('pt_BR', {
      custom: {
        cpf: {
          required: 'Favor preencher o cpf'
        }
      }
    })
    

    That will display your localized message when the field is empty.

    Here's an example of a field specific error message (replace 'en' with 'pt_BR' as needed)

    VeeValidate.Validator.localize('en', {
      custom: {
        cpf: {
          required: 'Favor preencher o cpf'
        }
      }
    })
    
    Vue.use(VeeValidate)
    
    new Vue({
      el: '#app'
    })
    p {
      color:red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script src="https://unpkg.com/vee-validate@latest"></script>
    <div id="app">
      <input type="text" data-vv-name="cpf" v-validate="'required'">
      <p>{{ errors.first('cpf') }}</p>
    </div>