Search code examples
vue.jsvuelidate

Vuelidate: multiple Step form validation


I'm using Vuelidate for my form validation.

It is a multiple-step form, but in the step 2 which there isn't input to valid, when I clicked next step button, I can't go to the step 3.

What may be wrong with my code?

    <section v-show="step === 1">
        <h3>Step 1</h3>
        <div class="name">
            <h4>Name</h4>
            <input v-model="name" @blur="$v.name.$touch" type="text" class="form-control form-control-lg">
            <p v-if="$v.name.$error" class="error-msg">Please fill the name</p>
        </div>
    </section>
    <section v-show="step === 2" class="step2">
        <h3>Step 2</h3>
        ...
    </section>
    
    <section v-show="step === 3" class="step3">
        <h3>Step 3</h3>
            <div class="tele">
                <label for="contact-tele">Telephone</label>
                <input v-model="phone" @blur="$v.phone.$touch" type="text" class="form-control form-control-lg">
                <p v-if="$v.phone.$error" class="error-msg">Please fill your telephone number</p>
            </div>
    </section>

<button class="next-step no-print" @click.prevent="nextStep" v-if="step != totalSteps>Next Step</button>

My vue code

methods: {
        nextStep: function() {
            if (this.step = 1) {
                if (this.$v.name.$invalid) {
                    return false;
                } else {
                    return this.step = 2;
                }
            }

            if (this.step = 3) {
                if (this.$v.phone.$invalid) {
                    return false;
                } else {
                    return this.step = 3;
                }
            }
            this.step++;
        },
   
    },

Solution

  • Here you are using a single = that assigns to this.step the values that you want to check for (1 and 3), while you should use a triple === to check the value.

    //if (this.step = 1) {
    if (this.step === 1) {
        if (this.$v.name.$invalid) {
            return false;
        } else {
            return this.step = 2;
        }
    }
    
    //if (this.step = 3) {
    if (this.step === 3) {
        if (this.$v.phone.$invalid) {
            return false;
        } else {
            return this.step = 3;
        }
    }
    this.step++;
    

    Read more bout the difference between =, == & ===here.