Using Vee-validate to disable button until form is filled out correctly

Green_qaue picture Green_qaue · Nov 8, 2017 · Viewed 20.5k times · Source

I want to disable my submit button until my form is filled out correctly, this is what I have so far:

<form>
   <input type="text" class="form-control" v-validate="'required|email'" name="email" placeholder="Email" v-model="userCreate.userPrincipalName" />
   <span v-show="errors.has('email')">{{ errors.first('email') }}</span>
   <button v-if="errors.any()" disabled="disabled" class="btn btn-primary" v-on:click="sendInvite();" data-dismiss="modal" type="submit">Send Invite</button>
   <button v-else="errors.any()" class="btn btn-primary" v-on:click="sendInvite();" data-dismiss="modal" type="submit">Send Invite</button>
</form>

The above only prints an error message and disables my submit button after I've started inputting a value. I need it to be disabled from the start, before I start interacting with the input, so that I cannot send an empty string.

Another question is if there is a better way than using v-ifto do this?

EDIT:

 userCreate: {
        customerId: null,
        userPrincipalName: '',
        name: 'unknown',
        isAdmin: false,
        isGlobalAdmin: false,
        parkIds: []
    }

Answer

brenthompson2 picture brenthompson2 · Mar 1, 2019

Setting up the button to be :disabled:"errors.any()" disables the button after validation. However, when the component first loads it will still be enabled.

Running this.$validator.validate() in the mounted() method, as @im_tsm suggests, causes the form to validate on startup and immediately show the error messages. That solution will cause the form to look pretty ugly. Also, the Object.keys(this.fields).some(key => this.fields[key].invalid); syntax is super ugly.


Instead, run the validator when the button is clicked, get the validity in the promise, and then use it in a conditional. With this solution, the form looks clean on startup but if they click the button it will show the errors and disable the button.

<button :disabled="errors.any()" v-on:click="sendInvite();">
    Send Invite
</button>
sendInvite() {
    this.$validator.validate().then(valid=> {
        if (valid) {
            ...
        }
    })
}

Validator API