zambliner
zambliner

Reputation: 466

Backbone Validation not working

I am working with Backbone.js 1.1.2

And have the View as follows:

'use strict';

define(['app/models/Frame', 'app/views/InitialView'], function(Frame, InitialView){

    var AppView = Backbone.View.extend({
        el: '.container',       

        template: _.template($('#appViewTemplate').html()),

        events: {
            'click #exitButton': 'exitApplication',
            'click #addScoreButton': 'handleScores'
        },

        initialize: function(){
            this.render();
        },

        handleScores: function(){

            var score = $('#score').val();

            var frame = new Frame({score: score}, {validate: true});


            frame.on('invalid', function(error){
                console.log('dfsdfdsfds');
            });

            this.collection.add(frame);         

            this.getScoreTable();

        },

        getScoreTable: function(){

            Backbone.sync('create', this.collection, {
                error: function(d){
                    //console.log(d);
                },
                success: function(frames){                  
                    console.log(frames);                    
                }
            });
        },

        exitApplication: function(){
            location.reload();
        },

        render: function(){
            this.$el.html(this.template);
            return this;
        }
    });

    return AppView;

});

And the Model as follows:

'use strict';

define([], function(){

    var Frame = Backbone.Model.extend({

        validate: function(attrs, options){

            if(attrs.score < 0){
                return 'No negative numbers please.';
            }           
        }
    });

    return Frame;
});

The problem I am facing is the validation not being triggred. I have tried almost all of the solutions available like changing to error, invalid, using on('invalid', function(){}). Also tried using the frame.validate() function which indeed called the validate function but when I tried to access the model attributes it returned undefined.

But still it is not working. I don't know what I am doing it wrong. Any help would be greatly appreciated.

Upvotes: 0

Views: 117

Answers (1)

nikoshr
nikoshr

Reputation: 33344

  • A Backbone constructor does not validate its values and lets you instantiate your model as you wish
  • Your error handling isn't attached at that point anyway
  • Validation will occur before you save and before a set if {validate:true} is passed as option.

So, you could write your handleScores function like this:

var frame = new Frame();

frame.on('invalid', function(model, error){
    console.log(model.toJSON(), error);
});

frame.set({score: score}, {validate: true});

And a demo http://jsfiddle.net/nikoshr/ozykLfxz/

Upvotes: 1

Related Questions