Vue.js和Vee Validate-如何使用API​​中的错误更新错误消息

时间:2018-07-30 16:33:39

标签: vue.js vee-validate

我正在尝试将错误信息从vee-validate设置为来自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>

因此,如果API返回电子邮件错误,我想将上述“ errors.first('email')”编辑为API错误。然后,当用户开始更正该字段时,Vee Validate将显示其配置的错误。

这是可能出现的一系列错误的示例:

[
  {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"}
]

如何处理API错误消息?

感谢您的时间和精力。

1 个答案:

答案 0 :(得分:0)

也许是这样-创建一个新的验证器,该验证器检查API是否返回了错误消息,如果是,则返回该错误消息。然后,将此新的验证器用作您的字段的第一个验证器,还要添加电子邮件地址的内置验证器。

<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>

更新

如果您要支持一系列错误,那么也许可以这样做

<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>