Ken Ramirez
Ken Ramirez

Reputation: 335

Error message showing after cleannig inputs with Vue

I have a simple form to update a password with 3 inputs (old_password, new_password and new_password_confirmation).

After the submit, if it is updated successfully, the inputs are cleaned. The problem is that after this, the input errors are showed even when the conditional is false.

This is one of the inputs:

<input type="password" v-model="old_password">
<small class="text-danger" v-if="errors.old_password != ''">{{errors.old_password}}</small>

The logic:

<script>
export default {
    data() {
        return {
            old_password: '',
            errors: []
        }
    },
    watch: {
        old_password(value) {
            this.old_password = value

            if(value.length < 3) {
                this.errors.old_password = 'Debes ingresar al menos 4 caracteres'
            } else {
                this.errors.old_password = ''
            }
        }
    },
    methods: {
        updatePassword() {
            this.$store.dispatch('updatePassword', data)
            .then(response => {
                this.old_password = ''
                this.errors.old_password = ''
            })
            .catch(error => {
            })
        }
    }
}
</script>

Upvotes: 0

Views: 36

Answers (1)

Andrew
Andrew

Reputation: 104

Because once input becomes empty your condition value.length < 3 is true and error will be shown

Simply add to your condition this one && value.length > 0 So the final code will look like

if(value.length < 3 && value.length > 0) {
  this.errors.old_password = 'Debes ingresar al menos 4 caracteres'
} else {
  this.errors.old_password = ''
}

Also, errors should be an object instead of an array - errors: {}

Upvotes: 1

Related Questions