thedersen/backbone.validation — Issue #22: Validating related attribute
Author: berzniz
Created: 2012-02-08 16:26:27+00:00
State: open

The original Backbone Model's validate method allows to validate attributes based on another:

```javascript
validate: function(attrs) {
if (attrs.end < attrs.start) {
return "can't end before it starts";
}
}
```
In the above example, the attributes [start] and [end] are validated together. The [start] can't be validated alone, it depends on the [end] value.

**With backbone.validation this is not possible.**

One solution that does **NOT** work is trying to do this:

```javascript
validation: {
start: function {value, attr} {
if (this.get('end') < value) {
return "can't end before it starts";
}
},
end: function {value, attr} {
if (this.get('start') > value) {
return "can't end before it starts";
}
}
}
```

It doesn't work since the .get() method returns the value currently set on the model and not the new value from the "attrs" array.

Any ideas?

I can suggest adding an optional "model" attribute to the validation:

```javascript
validation: {
name: {
maxlength: 50
},
age: {
min: 40
},
model: function (attrs) {
// here we can examine the model's attributes: name, age, start, end and so on...
if (attrs.end < attrs.start) {
return "can't end before it starts";
}
}
}
```