只有当所有项目都是数字时,我才想将一些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;
}
}
但是我检查其中一张选票是否不是数字的验证不起作用,代码继续在数据库中发布和保存数据!我做错了什么?
此外我想添加更多验证:所有投票都应该是唯一的。
最佳答案
问题出在您的 validate_votes
函数上。使用 $.each
函数时,第一个参数是项目的索引,第二个参数是项目本身。因此,如果 votes 是一个等于 ['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;
}
关于javascript - 简单的 Vuejs 验证代码无法按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44924747/