对于主干 v.1.0.0
var Man = Backbone.Model.extend({
initialize : function(){
this.on("invalid",function(model,error){
alert(error);
});
},
validate : function(attrs, options){
if (attrs.age < 18){
return 'below 18';
}
}
});
示例 1. 没有 {validate:true}
//Object will be created with invalid attribute 'age'
var man = new Man({name : 'qian', age : 12});
console.log(man) // Returns an object with invalid attributes
// But we'll use only valid objects.
// Also we'll get the error message in alert, if validation fails.
if(man.isValid()){
alert( man.get('name') );
}
var man = new Man({name : 'qian', age : 19});
if(man.isValid()){
alert( man.get('name') );
}
示例 2. 使用 {validate:true}
//Object will be created without any passed attributes
var man = new Man({name : 'qian', age : 12}, {validate:true});
console.log(man) //Object will be without passed attributes
/* man.isValid() returns 'true' throw we passed invalid attrs.
We won't see any error alert message, because Backbone created empty object */
/* Doesn't work */
if(man.isValid()){
alert( man.get('name') ); //undefined
}
/* Works */
// Created model had invalid attrs, so validationError won't be empty.
// If all attrs are valid, validationError will be empty
if(!man.validationError){
alert( man.get('name') );
}