backbone.validation
backbone.validation copied to clipboard
isNew and changed attrs
Hi
When the validation is running on a new model with unchanged attributes the validation isnt applied correctly.
When I debug validate i can see all correct errors in result.invalidAttrs but because changedAttrs is empty because the model is brand new and not changed the validation slips through and the model is saved to the server anyway
Backbone 1.0
I am seeing this as well. It comes down to this check here:
https://github.com/thedersen/backbone.validation/blob/master/dist/backbone-validation-amd.js#L263
I am going to have to figure out a workaround and report back.
I decided to just hack this part out:
&& _.intersection(_.keys(result.invalidAttrs), _.keys(changedAttrs)).length > 0
Hi, we also encounter problems with this peace of code && _.intersection(_.keys(result.invalidAttrs), _.keys(changedAttrs)).length > 0.
In our case it seems to be the same problem as issue #220.
We need a fix for this, is it possible to apply @cmwelsh's fix (&& _.size(result.invalidAttrs) > 0) quickly ?
Tried to apply @cmwelsh's but unit test fails, so its not a good fix.
In our case the problem is encountered when we validate a model where attributes are not defined.
var ModelClass = Backbone.Model.extend({
validation : {
name : {
required : true
}
}
});
...
var model = new ModelClass();
if(model.save() === false) {
// We should enter here but the _intersection instruction prevent it
}
As a workaround we simply define default values in our model classes.
var ModelClass = Backbone.Model.extend({
defaults : {
name : undefined
},
validation : {
name : {
required : true
}
}
})
...
var model = new ModelClass();
if(model.save() === false) {
// Now we should enter here
}
Hope this helps.
@bgaillard Your fix is good when your attributes aren't dynamic. Anyway, this is a known-issue and we're working on it. Also reported by https://github.com/thedersen/backbone.validation/issues/188.
Hi @chiefGui, I didn't remember I posted this :-) Happy to see the library is regularly updated now, we use it in several projects and it helps us a lot, thanks.
Hey @bgaillard!
I'm glad to know that you use it in your projects. Lots of things are about to come — stay in sync! :smile:
What about changing the line
if (!opt.forceUpdate && _.intersection(_.keys(result.invalidAttrs), _.keys(changedAttrs)).length > 0) {
to this:
if (!opt.forceUpdate && _.intersection(_.keys(result.invalidAttrs), _.keys(validatedAttrs)).length > 0) {
?
So I did and I'm testing it in my app. The validatedAttrs stands in direct relation to invalidAttrs and this way I don't have to define "extra" defaults on the model.
@chk- Feel free to write up a pull request if you think that approach will work!