Ahmad Mobaraki
Ahmad Mobaraki

Reputation: 8160

Simple Vuejs Validation code not working as expected?

I want to post some js objects to backend only if all items are numbers , here is the code :

  var MyApp = new Vue({

        el: '#my_element',
        data: {
            errors: [],
            votes: []
        },

        methods: {
           send_votes: function(){ 
             if(this.validate_votes(this.votes) === true){ 
                 return this.$http.post('/vote', this.votes).then(
                     function (response) {
                          // success message
                     },
                     function (error) {
                          // error message
                      }
                 )
              },
            }

        },

        validate_votes : function (votes) {

                var all_votes_are_number = true;
                $.each(votes, function (item) {
                    if(isNaN(item)){
                        all_votes_are_number = false;
                        MyApp.errors.push('one of votes is not a number');
                    }
                })

                return all_votes_are_number;
         }

   }

But My validation to check if one of votes is not a number, does not work and code continue posting and saving data in db! what am I doing wrong ?

Also I want to add more validation: all votes should be unique.

Upvotes: 0

Views: 58

Answers (1)

aprouja1
aprouja1

Reputation: 1810

The issue is your validate_votes function. When using the $.each function, the first argument is the index of the item, and the second argument is the item itself. So if votes was an array equal to ['A','B','C'] you would be checking against 0,1,2. Try the below instead:

validate_votes : function (votes) {

                var all_votes_are_number = true;
                $.each(votes, function (item, el) {
                    if(isNaN(el)){
                        all_votes_are_number = false;
                        MyApp.errors.push('one of votes is not a number');
                    }
                });

                return all_votes_are_number;
         }

Upvotes: 1

Related Questions