M
M
Maxim Torbeev2015-09-23 10:20:05
JavaScript
Maxim Torbeev, 2015-09-23 10:20:05

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';
        }
    }
});

Naturally created a collection:
App.Collections.Contacts = Backbone.Collection.extend({
    models: App.Models.Contact,
    url: '/contacts'
})

Well, then the view:
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 });
    }

})

In principle, I did everything according to the video from the LoftBlog team in 2013 (Respect to the guys), they used there (at the present time) an old version of the backbone. As far as I understand, validation in the set method, and by itself create is disabled by default. So the question is: How to use this very validation?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2015-09-23
@k12th

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 question

Ask a Question

731 491 924 answers to any question