【问题标题】:Loopback conditional data validation环回条件数据验证
【发布时间】:2018-02-01 03:05:56
【问题描述】:

如何根据请求正文中的某些条件定义一些验证规则。
例如,我想验证仅在发布帖子时才设置帖子描述字段(isPublished 标志等于 true),例如:

module.exports = function(Post) {
if(req.body.isPublished === true) {
    Post.validatesPresenceOf('description');
  }
}

【问题讨论】:

  • 您能详细说明一下吗?
  • @nitte93user3232918 我已经详细说明了。

标签: javascript strongloop loopback


【解决方案1】:

很简单,可以使用options参数

Post.validatesPresenceOf('description', {if: 'isPublished'});

参考:#validatable-validatespresenceof

【讨论】:

    【解决方案2】:

    也许你正在寻找这样的东西

    Post.observe('before save',(ctx,next)=>{
      //if post is created
      if(ctx.isNewInstance) {
        if(ctx.instance.isPublished)
          Post.validatesPresenceOf('description');
      }
      //if post is updated
      else{
        if(ctx.data.isPublished)
          Post.validatesPresenceOf('description');
      }
    return next();
    })
    

    【讨论】:

    • 我试过了,每次调用“验证...”方法时,它似乎都会对模型的所有未来实例添加验证检查,然后忽略此代码中的 if 条件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多