Search code examples
vuejs2vuelidate

Vuelidate how to conditionally disable submit button


How can I conditionally disable the submit button of my Vuelidate form if all the fields don't meet the required criteria?

I tried the below but :disabled will only accept the word disabled in there.

<form>
  <ol>
    <li class="inputQuestion" v-bind:class="{ 'error': $v.user.username.$error }">
      <label>Username:</label>
      <input v-model.trim="user.username" @input="$v.user.username.$touch()" />
    </li>
    <li class="inputQuestion" v-bind:class="{ 'error': $v.user.password.$error }">
      <label>Password:</label>
      <input v-model.trim="user.password" @input="$v.user.password.$touch()" />
    </li>

    <li class="submission">
      <button @click.prevent="submitForm" :disabled="$v.form.valid()">Sign In</button>
    </li>
  </ol>
</form>

Solution

  • Currently, you are binding disabled to the value returned by $v.form.valid(), which will only be run once when the component's template is rendered and won't change after that point.

    From the Vuelidate documentation, it looks like you are provided a $invalid property for the form model which:

    Indicates the state of validation for given model. becomes true when any of it's child validators specified in options returns a falsy value. In case of validation groups, all grouped validators are considered.

    Use that instead:

    <button @click.prevent="submitForm" :disabled="$v.form.$invalid">