简体   繁体   中英

Backbone 0.9.9 validate model on create new Model

After update to the new Backbone version 0.9.9 there is the problem that when I want to create a new model it always get into the validate function. Eg I set "title" in defaults and "title":"" and in validate I want to check if there is a length. If on startup the validate function is run, then there will always be a error.

What could I do?

You could allow empty title in your validate method, or you always instantiate your models with values, eg: new Model({ title: 'my title' })

In the worse scenario, you can check if model is fetched or not, by example:

validate: function( attrs ) {
  if( this.fetched ) {
    if( !attrs.title.length ) { return "error!"; }
  }
}

Then, you would just have to setup this.fetched to true when you've get all your information and build your model correctly.

But the fact is that your defaults value should be in valid format from the start.

edit after discution in comments
You could probably also check the hasChanged function from Backbone.model to allow validation or not. For example:

validate: function( attrs ) {
  if( this.hasChanged() ) {
    if( !attrs.title.length ) { return "error!"; }
  }
}

This way, you'll skip the validation on initialization, and then, it'll only validate when you set new values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM