I have a model and I'm trying to use Backbone.Validation
to validate the attributes of the model :
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;
});
Here is the view :
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;
});
When I click on button submit without fill in Name
field, there's no error in my console; otherwise, successfully message is show in console.
I didn't find any sample about calling backbone.validate
in model initialize function.
Any help is much appreciated. Thanks.
if i'm seeing this correct, you are new-ing the model with all the data; and saving null. The validation runs on save, you are not saving anything. Put the name in the save.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.