我想将一些js对象发布到后端只有当所有项都是数字时,这里是代码:
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;
}
}
但是我的验证检查其中一个投票是否不是数字,不起作用,代码继续发布并在db中保存数据!我做错了什么?
我想添加更多验证:所有投票都应该是唯一的。
答案 0 :(得分:1)
问题在于您的validate_votes
功能。使用$.each
函数时,第一个参数是项的索引,第二个参数是项本身。因此,如果投票是一个等于['A','B','C']
的数组,那么你将检查0,1,2。请尝试以下代码:
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;
}