在vuetify

时间:2018-01-31 05:01:05

标签: javascript vue.js vuejs2 vuetify.js vuelidate

你们是如何在Vuetify中进行验证的? 我无法用非常详细的验证语法来解决这个问题。

我正在使用Vuelidate,根据Vuetify的文档,以下是我必须实现一个简单的必填字段:

脚本:

import { required } from 'vuelidate/lib/validators';

computed: {
    userNameErrors() {
      const errors = []
      if (!this.$v.loginForm.userName.$dirty) {
        return errors
      }
      !this.$v.loginForm.userName.required && errors.push('This field is required')
      return errors
    }
},
validations: {
    loginForm: {
      userName: {
        required
      }
    }
  }

模板:

 <v-text-field :label="Username"
                    prepend-icon="account_circle"
                    v-model="loginForm.userName"
                    :error-messages="userNameErrors"
                    @input="$v.loginForm.userName.$touch()"
                    @blur="$v.loginForm.userName.$touch()"
                    :required="true"></v-text-field>

我觉得非常冗长。我可能会采取错误的方式,任何人都可以告诉你,你是如何制作这种简约或短手的?

P.S。我来自Angular1背景,ng-messages非常酷且简单!

2 个答案:

答案 0 :(得分:2)

我提出了以下解决方案来处理通用验证:

function handleErrors(fieldName, vueObj) {
  const errors = []
  if (!vueObj.$v[fieldName].$dirty) return errors
  if ('email' in vueObj.$v[fieldName]) {
    !vueObj.$v[fieldName].email && errors.push('This email address is invalid')
  }
  if ('required' in vueObj.$v[fieldName]) {
    !vueObj.$v[fieldName].required && errors.push('This field is required')
  }
  if (fieldName in vueObj.serverErrors) {
    vueObj.serverErrors[fieldName].forEach(error => {
      errors.push(error)  
    });
  }
  return errors
}

然后可以在Vue对象中使用它:

...
computed: {
    emailErrors () {
      return handleErrors('email', this)
    },
  },
...

然后,您必须处理handleError中可能的错误类型(在示例中处理了必需和电子邮件验证程序)。我还使用它来显示从后端返回的字段错误。

我也很好奇这是否可以更容易解决!

答案 1 :(得分:0)

我只是在这里建议,但是使用vuelidate-errors-extractor会使它更简单

相关问题