1
votes

I am trying to set the error message from the vee-validate to one from an API.

<div class="col-md-12">
  <label for="company-contact-name" class="label-input">Company Contact Name</label>
  <input v-validate="validations.user.name" v-model="data.user.name" id="company-contact-name" class="form-control" type="text" name="name" placeholder="Enter contact name" />
  <div id="name-error" class="msg-error text-danger">{{ errors.first('name') }}</div>
</div>


<div class="col-md-12">
  <label for="email" class="label-input">E-mail address</label>
  <input v-validate="validations.user.email" v-model="data.user.email" id="email" class="form-control" type="email" name="email" placeholder="Enter e-mail" />
  <div id="email-error" class="msg-error text-danger">{{ errors.first('email') }}</div>
</div>

So, If the API returns an email error, I would like to edit the above "errors.first('email')" to the API error. Then, when the user starts to correct the field, the Vee Validate would show its configured errors.

This is an example of a possible array of errors:

[
  {id: "name", title: "Name is invalid. It should have only letters"},
  {id: "name", title: "Name is too short. It should have more than three characters"},
  {id: "email", title: "Email has already been taken"}
]

What can be done to handle the API error messages?

Thanks for your time and attention.

1
You simply assign the error message from the API and add one more validator for the email which will simply return the value of the above variable.IVO GELOV
@IVOGELO, could you give me an example? I just started to learn Vue.js and this library. Thanks.Kelvin Matheus

1 Answers

0
votes

Perhaps something like this - create a new validator which checks whether the API has returned an error message and if yes - returns that error message. Then use this new validator as a first validator for your field, but also add the built-in validator for email addresses.

<input 
  v-validate="api_email|email" 
  v-model="user.email" 
  id="email" 
  class="form-control" 
  type="email" 
  name="email" 
  placeholder="Enter e-mail" />

<script>
import { Validator } from 'vee-validate';

export default
{
  data()
  {
    api_error: '',
    user:
    {
      email: ''
    }
  },
  mounted()
  {
    Validator.extend('api_email', 
    {
      getMessage: this.emailError,
      validate: this.validateEmail
    });
  },
  methods:
  {
    validateEmail(value, args)
    {
      return !this.api_error;
    },
    emailError(field, args)
    {
      return this.api_error;
    }
  }
}
</script>

UPDATE

If you want to support an array of errors then perhaps you can do it like this

<div id="email-error" class="msg-error text-danger" v-for="err in [errors.first('email')].concat(array_with_api_errors.map(item => item.title))">{{ err }}</div>