javascript 使用vuetify验证多字段形式的单个字段

ffscu2ro  于 2023-02-18  发布在  Java
关注(0)|答案(1)|浏览(166)

我有一个emailValidation方法,我想在this.$refs.editUserForm.validate('email')为true时运行该方法,但如果我输入的电子邮件为jack@xyz.com或任何有效的电子邮件,它总是返回this.$refs.editUserForm.validate('email')为false。请帮助我了解如何检查表单中单个字段的验证。

<template>
  <v-form ref="editUserForm" :model="user" data-app>
    <v-text-field
      v-model="user.first_name"
      label="First Name"
      :rules="firstNameRules"
      class="required"
      required
    >
    </v-text-field>
    <v-text-field
      v-model="user.email"
      label="Email"
      :rules="emailRules"
      name="email"
      class="required"
      required
      @blur="emailValidation"
    >
    </v-text-field>
  </v-form>
</template>
<script>
export default {
  data: function () {
    return {
      client: {
        first_name: '',
        email: ''
      },
      firstNameRules: [
        value => !!value || 'Please enter a first name'
      ],
      emailRules: [ 
        v => /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(v) || 'E-mail must 
        be valid'
      ]
    };
  },

  methods: {
    emailValidation(){
      if (this.$refs.editUserForm.validate('email')) {
        console.log("Valid")
      }
      else {
        console.log("Not Valid")
      }
    }
  }
};
</script>
7lrncoxx

7lrncoxx1#

问题是表单的validate函数不接受字符串,它总是验证整个表单并返回结果,所以即使email字段有效,如果其他字段无效,它仍然会返回false。
要只验证一个字段,需要为该字段提供一个ref,并只在该字段的ref上调用validate()

<v-text-field
  ref="email"
  v-model="user.email"
  label="Email"
  :rules="emailRules"
  name="email"
  class="required"
  required
  @blur="emailValidation"
>
</v-text-field>

验证代码也取决于您的Vuetify版本:
验证2.x

emailValidation() {
  const valid = this.$refs.email.validate();
  if (valid) {
    console.log('Valid');
  } else {
    console.log('Not Valid');
  }
}

验证3.x
validate()返回承诺,因此必须使用async/await

async emailValidation() {
  const valid = await this.$refs.email.validate();
  // valid is as an array of possible error messages. A length of 0 indicates valid input
  if (valid.length === 0) {
    console.log('Valid');
  } else {
    console.log('Not Valid');
  }
}

相关问题