有什么办法可以通过 NOT REQUIRED v-text-field 规则的验证吗?

问题描述 投票:0回答:3

我尝试验证 v-text-field 仅用于输入数字,但它不是必需的,但规则拒绝通过验证。

我使用了 v-form、v-text-field 和 v-text-field 规则。

<template>
  <v-form ref="form">
    <v-text-field
      v-model="name"
      :label="label"
      :rules="rules"
      @blur="changeValue"
      clearable
    ></v-text-field>
  <v-btn @click="send">submit</v-btn>
</v-form>
</template>

<script>
export default {
  data() {
    return {
      name: "",
      rules: [
        v =>
          v.length <= 50 || "maximum 50 characters",
        v =>
          (v.length > 0 && /^[0-9]+$/.test(v)) || "numbers only"
      ]
    };
  },
  methods: {
    changeValue(event) {
      this.$emit("changeValue", event.target.value);
    },
    send() {
      const valid = this.$refs["form"].validate(); // doesn't pass
      if (valid) {
        this.$store.dispatch("xxx", {
          ...
        });
      }
    }
  }
};
</script>

单击提交按钮时,会显示 v-text-field 的错误消息,并且

valid
为 false。

单击X(清除图标),错误消息也显示在控制台上:

"TypeError: Cannot read property 'length' of null"
forms validation textfield vuetify.js
3个回答
8
投票

有点晚了,但我已经用这个函数解决了它:

rules: [
  v => {
    if (v) return v.length <= 50 || 'maximum 50 characters';
    else return true;
  },
],

1
投票

我用这种方式,一种用于电子邮件,另一种用于姓名

nameRules: [  
  v => v.length <= 10 || 'Name must be less than 10 characters',
],
emailRules: [      
  v =>( v.length ===0 || /.+@.+/.test(v) )   || 'E-mail must be valid',
],

0
投票

通过在任何规则中添加

!v || 
,您可以使其“不是必需的,但如果存在,则必须遵循该规则”。 这是您的规则部分的代码:

rules: [
        v => !v || (v && v.length <= 50) || `Maximum 50 characters`,
        v => !v || (v && v.length > 0 && /^[0-9]+$/.test(v)) || "numbers only"
]
© www.soinside.com 2019 - 2024. All rights reserved.