Backbone.js验证模型
我预计,在视图中调用model.set()方法时,验证函数应该运行, 但我使用下面的代码进行测试,它从不调用模型中定义的验证函数。 有人知道我做错了什么吗Backbone.js验证模型,backbone.js,Backbone.js,我预计,在视图中调用model.set()方法时,验证函数应该运行, 但我使用下面的代码进行测试,它从不调用模型中定义的验证函数。 有人知道我做错了什么吗 <!doctype html> <html> <head> <meta charset=utf-8> <title>Form Validation - Model#validate</title> <script src='http://code.jqu
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Form Validation - Model#validate</title>
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
<script>
jQuery(function($) {
var User = Backbone.Model.extend({
validate: function(attrs) {
var errors = this.errors = {};
console.log('This line is never called!!!');
if (!attrs.firstname) errors.firstname = 'firstname is required';
if (!attrs.lastname) errors.lastname = 'lastname is required';
if (!attrs.email) errors.email = 'email is required';
if (!_.isEmpty(errors)) return errors;
}
});
var Field = Backbone.View.extend({
events: {blur: 'validate'},
initialize: function() {
this.name = this.$el.attr('name');
this.$msg = $('[data-msg=' + this.name + ']');
},
validate: function() {
this.model.set(this.name, this.$el.val());
//this.$msg.text(this.model.errors[this.name] || '');
}
});
var user = new User;
$('input').each(function() {
new Field({el: this, model: user});
});
});
</script>
</head>
<body>
<form>
<label>First Name</label>
<input name='firstname'>
<span data-msg='firstname'></span>
<br>
<label>Last Name</label>
<input name='lastname'>
<span data-msg='lastname'></span>
<br>
<label>Email</label>
<input name='email'>
<span data-msg='email'></span>
</form>
</body>
</html>
表单验证-模型#验证
jQuery(函数($){
var User=Backbone.Model.extend({
验证:函数(attrs){
var errors=this.errors={};
console.log('从未调用此行!!!');
如果(!attrs.firstname)出现错误,则.firstname='firstname是必需的';
如果(!attrs.lastname)errors.lastname='lastname是必需的';
如果(!attrs.email)errors.email='需要电子邮件';
if(!\ isEmpty(errors))返回错误;
}
});
变量字段=主干.View.extend({
事件:{blur:'validate'},
初始化:函数(){
this.name=this.$el.attr('name');
this.$msg=$('[data msg='+this.name+']');
},
验证:函数(){
this.model.set(this.name,this.el.val());
//this.$msg.text(this.model.errors[this.name]| |“”);
}
});
var user=新用户;
$('input')。每个(函数(){
新字段({el:this,model:user});
});
});
名字
姓
电子邮件
从主干网0.9.10开始,只有在默认情况下保存时才调用validate。如果要在设置属性时对其进行验证,则需要传递{validate:true}
选项
var Field = Backbone.View.extend({
// ..
validate: function() {
this.model.set(this.name, this.$el.val(), {validate: true});
//this.$msg.text(this.model.errors[this.name] || '');
}
});