Search code examples
formsvalidationtextfieldvuetify.js

Is there any way to pass the validation of NOT REQUIRED v-text-field rules?


I tried to validate v-text-field for entering number only but it is not required but the rules deny to pass the validation.

I used v-form, v-text-field and rules of 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>

When the submit button was clicked, error message of v-text-field is shown and valid is false.

Clicked X(the clear icon), The error message is also shown on console:

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

Solution

  • A bit late, but i have solved it with this function:

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