Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Validation with Backbone stickit - All attributes being validated when one is changed

I am attempting to use Backbone Validation with Backbone Stickit, I wish to validate one attribute at a time as the user enters them. However, when a user enters a value all attributes on the model get validated instead of just the one the user has changed. What am I doing wrong?

My View:

bindings:{
        '#username' : {
           observe:'username',
           setOptions: {
                validate:true
           }
        },

        '#email' : {
           observe:'email',
           setOptions: {
                validate:true
           }
        },

        '#firstname' : {
           observe:'firstName',
           setOptions: {
                validate:true
           }
        }, 

.......

onShow: function(){    
        Backbone.Validation.bind(this, {
              valid: function(view, attr) {
                alert('VALID - ' + attr);
              },
              invalid: function(view, attr, error) {
                alert('INVALID - ' + attr);
              }
            });

        this.stickit();

    },
like image 982
Francium123 Avatar asked Feb 07 '14 21:02

Francium123


3 Answers

Everything you pass through setOptions is used when setting the value in the model (1). When you pass validate: true to the set function of a Backbone model it will validate the values in the model as well as the values passed to the set function (2) meaning it will validate the whole model every time you set a new value causing the problem you're seeing now. You're not doing anything wrong.

You could probably solve this by splitting up your validation into multiple separate functions and calling only the required ones on attribute change and then changing the validate function to call all those separate functions to validate the entire model.

like image 87
yousefcisco Avatar answered Nov 07 '22 06:11

yousefcisco


This happened to me as well. In my case, I was setting default values in the model as '' (blank). Removed them and it worked

like image 35
Bharath Bhandarkar Avatar answered Nov 07 '22 06:11

Bharath Bhandarkar


For this to work you should remove defaults (at least for the attributes your validating) values from your model

like image 33
erratbi Avatar answered Nov 07 '22 07:11

erratbi