【问题标题】:Is there any way to pass the validation of NOT REQUIRED v-text-field rules?有没有办法通过 NOT REQUIRED v-text-field 规则的验证?
【发布时间】:2019-10-15 16:00:58
【问题描述】:

我尝试验证 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为假。

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

"TypeError: Cannot read property 'length' of null"

【问题讨论】:

    标签: forms validation textfield vuetify.js


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-09-08
        • 2021-03-01
        • 2020-10-10
        • 2017-02-23
        • 2021-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-22
        相关资源
        最近更新 更多