Answer the question
In order to leave comments, you need to log in
How to run validation in backbone.js 1.2.x when using create method?
Good time of the day.
I ran into a validation problem when using the collection.create method.
I created a model in which I used the validation method:
App.Models.Contact = Backbone.Model.extend({
validate: function(attrs, options) {
if (!attrs.first_name || !attrs.last_name) {
return "Укажите имя и фамилию";
}
if( !attrs.email_address){
return 'Пожалуйста введите валидный email';
}
}
});
App.Collections.Contacts = Backbone.Collection.extend({
models: App.Models.Contact,
url: '/contacts'
})
App.Views.AddContacts = Backbone.View.extend({
el: '#contacts-form',
events: {
'submit' : 'addContact'
},
addContact: function(e){
e.preventDefault();
var addContEvent = this.collection.create({
first_name: this.$('#first_name').val(),
last_name: this.$('#last_name').val(),
email_address: this.$('#email_address').val(),
description: this.$('#description').val()
}, { wait: true });
}
})
Answer the question
In order to leave comments, you need to log in
The documentation says that if the client validation fails, then the model is not saved.
If you look at the code, Collection#create calls Collection#_p;repareModel, and from there new this.model is called, and Model#set is called in the model's default constructor.
So that should work. If it doesn't work, then set breakpoints and see what happens.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question