0

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.

2
  • 1
    Are you sure you have checked the documentation for $.each? First parameter of the callback will be the index, not the item itself. Commented Jul 5, 2017 at 11:35
  • @MatJ thank you! crazy mistake, let me try Commented Jul 5, 2017 at 11:42

1 Answer 1

1

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;
         }
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, I get it, now what about Also I want to add more validation: all votes should be unique.

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.