简体   繁体   English

骨干0.9.9在创建新模型时验证模型

[英]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. 更新到新的Backbone版本0.9.9后,存在一个问题,当我想创建一个新模型时,它总是进入validate函数。 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' }) 您可以在validate方法中允许使用空标题,或者始终使用值实例化模型,例如: 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. 然后,当您获得所有信息并正确构建模型后,只需将this.fetched设置为true。

But the fact is that your defaults value should be in valid format from the start. 但是事实是, defaults值从一开始就应该采用有效格式。

edit after discution in comments 意见不一后编辑
You could probably also check the hasChanged function from Backbone.model to allow validation or not. 您可能还可以从Backbone.model检查hasChanged函数以允许或不允许进行验证。 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. 这样,您将跳过初始化时的验证,然后仅在set新值时进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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