[Vuejs]-Vue.js and Vee Validate – How to update error message with error from an API

0👍

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>

Leave a comment