繁体   English   中英

如何在Meteor中的自定义验证简单模式中检查布尔值是否为真

[英]How to check if boolean is true in custom validation simple-schema in Meteor

我有以下架构:

Games.attachSchema(new SimpleSchema({
    title: {
        type: String,
        label: "Title",
        max: 30
    },
    multiplayer: {
        type: Boolean,
        label: "Multiplayer",
        denyUpdate: true
    },
    description: {
        type: String,
        label: "Description",
        custom: function() {
            var multiplayer = this.field("multiplayer");
            if (multiplayer.isSet && multiplayer.value && !this.isSet) return "Description is empty!";
            return true;
        }
    }
}));

我的目标是检查description是否为空,但multiplayer是已选中复选框multiplayer 如果未选中该复选框,则description不是必须填写。

我尝试了上面的代码,但未通过验证。 即使我没有说明,并且选中了复选框,也可以提交表格。

我认为问题出在您的验证逻辑上。 尝试将其更改为:

if (multiplayer.isSet && multiplayer.value && this.isSet && this.value == "")
return "Description is empty!";

我找到了正确的文档,并按以下方式解决了它:

{
  description: {
    type: String,
    optional: true,
    custom: function () {
      var shouldBeRequired = this.field('multiplayer').value;

      if (shouldBeRequired) {
        // inserts
        if (!this.operator) {
          if (!this.isSet || this.value === null || this.value === "") return "required";
        }

        // updates
        else if (this.isSet) {
          if (this.operator === "$set" && this.value === null || this.value === "") return "required";
          if (this.operator === "$unset") return "required";
          if (this.operator === "$rename") return "required";
        }
      }
    }
  }
}

暂无
暂无

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

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