Zeth
Zeth

Reputation: 2598

Vuelidate doesn't update 'required'-validator, when inserting into input-field

TL;DR

When using the 'required'-validator, then it doesn't update, when I insert content into a text-field.

CodeSandbox: https://codesandbox.io/s/confident-benz-x1lq8?file=/src/App.vue


Further details

I'm experiencing a wierd bug - and I've been sitting with it all day! I'm afraid that I'm missing something obvious, but I'm starting to get the feeling, that it could be a bug in the Vuelidate-library.

I have a simple form like this:

<div class="field__container">
  <div>
    <label for="emailToInvite">Email to invite</label> <br />
    <input
      type="email"
      id="emailToInvite"
      name="emailToInvite"
      v-model="$v.emailToInvite.$model"
    />

    <div class="errors" v-if="showErrors">
      <p v-if="!$v.emailToInvite.required">Email to invite is required.</p>
      <p v-if="!$v.emailToInvite">The written email is not valid.</p>
    </div>
  </div>
</div>

<button type="button" @click="submitForm()">Submit</button>

and the logic:

import { required, email } from "vuelidate/lib/validators";

export default {
  data() {
    return {
      number: 1,
      showAll: false,
      submitAttempts: 0,
    };
  },
  computed: {
    showErrors() {
      if (this.submitAttempts > 0) {
        if (this.$v.$invalid) {
          return true;
        }
      }
      return false;
    },
  },
  methods: {
    submitForm() {
      this.submitAttempts++;
    },
    resetAll() {
      this.submitAttempts = 0;
      this.$v.emailToInvite.$model = "";
    },
  },
  validations: {
    emailToInvite: {
      required,
      email,
    },
  },
}

And when I insert some text in the emailToInvite-field, then the 'required'-validator stays 'false'.

Another wierd thing is that the 'email'-validator is true, when the input is just an empty string.

All this can be seen in this CodeSandbox: https://codesandbox.io/s/confident-benz-x1lq8?file=/src/App.vue

What am I doing wrong?

Upvotes: 1

Views: 1669

Answers (1)

Karin C
Karin C

Reputation: 505

I noticed a few things you should change -

First, you must add emailToInvite: '' to data:

data() {
  return {
    number: 1,
    showAll: false,
    submitAttempts: 0,
    emailToInvite: ''
  };
},

I'm not sure how Vuelidate works, but it seems it doesn't create the property for you. So it can't track the change properly.

Second, the showErrors computed property is set to 'false' until you press on 'Submit'. So you won't see the error message before you click on 'Submit'. Set it to 'true' if you want to see the error message (or hide it) while you type.

Upvotes: 2

Related Questions