Using Vee-validate to disable button until form is

2020-07-06 06:59发布

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: []
    }

7条回答
看我几分像从前
2楼-- · 2020-07-06 07:21

For the current version 3 (As at the time of writing).

Step 1

Ensure form fields can be watched.

Step 2

Get a reference to the validator instance: <ValidationObserver ref="validator">.

Step 3

Trigger validation silently whenever the form fields change.

Here's an example:

     export default {
        data() {
            return {
                form: {
                    isValid: false,
                    fields: {
                        name: '',
                        phone: '',
                    }
                }
            }
        },

        watch: {
            'form.fields': {
                deep: true,
                handler: function() {
                    this.updateFormValidity();
                }
            }
        },
        methods: {
            async updateFormValidity() {
                this.form.isValid = await this.$refs.validator.validate({
                    silent: true // Validate silently and don't cause observer errors to be updated. We only need true/false. No side effects.
                });
            },
        }
    }
<button :disabled="form.isValid">
    Submit
</button>
查看更多
登录 后发表回答