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();
},
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.
This happened to me as well. In my case, I was setting default values in the model as '' (blank). Removed them and it worked
For this to work you should remove defaults (at least for the attributes your validating) values from your model
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With