2

How can I add items to the hasErrors array if the input username or password are empty and remove them if the input are not empty so that the disabled class on the submit button is dynamically enabled/disabled?

<form>
    <input type="username" v-model="form.username">
    <input type="password" v-model="form.password">
    <input type="submit" :disabled="hasErrors.length > 0">
</form>

<script>
    var app = new Vue({
        el: '#app',
        data: {
            form: {
                username = '',
                password = '',
                hasErrors: []
            }
        }
    });
</script>

1 Answer 1

3

You can use computed property for this case:

<script>
    var app = new Vue({
        el: '#app',
        data: {
            form: {
                username: '',
                password: '',
            }
        },
        computed: {
            hasErrors: function(){
                var errors = [];
                if(this.form.username == '') errors.push('username');
                if(this.form.password == '') errors.push('password');
                return errors;
            }
        }
    })
</script>

then use

<input type="submit" :disabled="hasErrors.length > 0">
Sign up to request clarification or add additional context in comments.

2 Comments

hey, this definitely works. However, I think I found a bug in Vue, if I used a input type select multiple, and the v-model is inside an object, only the 1st selected item is being saved in the data. Let's say you are allowed to select multiple username, and the name of the v-model is "form.username". If I store it in username and not form.username, it works however
Use this validation plugin vee-validate.logaretm.com @KaySingian

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.