如何在Meteor中自定义验证simple-schema中检查boolean是否为true

时间:2015-10-01 14:21:04

标签: javascript meteor meteor-autoform meteor-collection2 simple-schema

我有以下架构:

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复选框时。如果未选中该复选框,则不应强制description填写。

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我找到了合适的documentation,我解决了这个问题:

{
  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";
        }
      }
    }
  }
}