我有一个模型,我尝试使用Backbone.Validation
来验证模型的属性:
define(["underscore" , "backbone","backbone.validation"],function(_ , Backbone, BackboneValidation){
var CustomerModel = Backbone.Model.extend({
urlRoot: getURL(),
initialize: function(){
this.on("error", function(model, error){
console.log(error);
});
},
validation: function() {
return {
Name: {
required: true,
msg: 'Please enter your name'
}
}
},
defaults : {
UID: "00000000-0000-0000-0000-000000000000",
Name: "",
Company: "",
Address: ""
}
});
return CustomerModel;
});
以下是观点:
define(["jquery" ,
"underscore" ,
"backbone" ,
"text!templates/Customer/register.html",
"models/CustomerModel",
"backbone.validation"
],function($ , _ , Backbone, Register, CustomerModel, BackboneValidation){
var RegisterView = Backbone.View.extend({
initialize : function(){
Backbone.Validation.bind(this, {
model: CustomerModel
});
},
events : {
'click #register' : 'register'
},
registerUser : function(e){
var _customer = new CustomerModel({
UID: "00000000-0000-0000-0000-000000000000",
Name: $("#firstname").val() + $("#lastname").val(),
Company: "",
Address: ""
});
_customer.save(null, {
success:function() {
console.log("successfully register!");
},
error : function(){
console.log("error!");
}
});
},
render : function(){
var _register= _.template(Register);
this.$el.html(_register());
return this;
}
});
return RegisterView;
});
当我点击按钮提交而不填写Name
字段时,我的控制台中没有错误;否则,成功的消息将显示在控制台中。
我没有找到关于在模型初始化函数中调用backbone.validate
的任何示例。
非常感谢任何帮助。感谢。
答案 0 :(得分:0)
如果我看到这是正确的,那么你正在使用所有数据来创建模型;并保存null。验证在保存时运行,您没有保存任何内容。将名称放在保存中。