我在Backbone验证方面遇到的问题很少,但似乎我找到了正确的方法。我设法实现了以下目标:
var EditUser = Backbone.View.extend({
el:'.page',
validates:function(evt){
console.log('here');
var $field = $(evt.currentTarget);
if($field.val() === ''){
$field.css('border', '1px solid red');
return false;
}
else{
$field.css('border', '1px solid #ccc');
}
},
render: function(options){
var that = this;
if(options.id){
that.user = new User({id: options.id});
that.user.fetch({
success: function(user){
var template = _.template($('#edit-user-template').html(), {user:user});
that.$el.html(template);
}
});
} else{
var template = _.template($('#edit-user-template').html(), {user:null});
this.$el.html(template);
}
},
events: {
'keyup input[name=firstname], input[name=lastname], input[name=age]': 'validates',
'submit .edit-user-form': 'saveUser',
'click .delete': 'deleteUser'
},
saveUser: function (ev){
this.$('input[type=text]').each(function() {
$(this).trigger('keyup');
});
var userDeatils = $(ev.currentTarget).serializeObject();
var user = new User({validate:true});
user.save(userDeatils,{
success: function(user){
router.navigate('', {trigger:true});
}
})
return false;
},
deleteUser: function(ev){
this.user.destroy({
success: function(){
router.navigate('', {trigger:true});
}
});
return false;
}
});
当我开始输入输入字段时,一切正常,但是当我提交表单时,我需要执行相同的操作。 (已经附加了saveUser)。我需要找到一种方法来运行验证蚂蚁,在调用“saveUser”之前停止提交带有空详细信息的表单
答案 0 :(得分:1)
如下所示更改validates
。
validates:function(evt, $field){
var valid = true;
if(evt)
$field = $(evt.currentTarget);
if($field.val() === ''){
$field.css('border', '1px solid red');
valid = false;
}
else{
$field.css('border', '1px solid #ccc');
}
return valid;
}
和saveUser
如下所示。
saveUser: function (ev){
var valid = true, that = this;
this.$('input[type=text]').each(function() {
valid = that.validates(null, $(this)); // validate input.
if (!valid) return false; //break out from loop.
});
if (valid) {
var userDeatils = $(ev.currentTarget).serializeObject();
var user = new User({validate:true});
user.save(userDeatils,{
success: function(user){
router.navigate('', {trigger:true});
}
});
}
return false;
}