Module 2: Model Validity

by emgee

HTML

<script src="http://documentcloud.github.com/underscore/underscore.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>

JavaScript

var Vehicle = Backbone.Model.extend({
    validate: function(attrs, options){
        var validColors = ["white", "red", "blue", "yellow"];
        var colorIsValid = function(attrs){
            if (!attrs.color) return true;
            return _(validColors).include(attrs.color);
        };
        if (!colorIsValid(attrs)){
            return "color must be one of: " + validColors.join(", ");
        }
    }
}); 

var car = new Vehicle();

car.on("invalid", function(model, error){
    console.log(error);
});

car.set("foo", "bar");

// set no longers calls the validate method, only save; to trigger validation on set specify the validate in
// options
car.set("color", "green", {validate:true});
console.log(car.get("color"));
car.set("color", "red", {validate:true});
console.log(car.get("color"));