如何在 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
已被选中。如果复选框没有被选中,description
不应该是强制填写的。
我试过上面的代码,但它没有生效。即使我没有描述并且勾选了复选框,我也可以提交表格。
我认为问题出在您的验证逻辑上。尝试将其更改为:
if (multiplayer.isSet && multiplayer.value && this.isSet && this.value == "")
return "Description is empty!";
我找到了正确的 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";
}
}
}
}
}
我有以下架构:
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
不应该是强制填写的。
我试过上面的代码,但它没有生效。即使我没有描述并且勾选了复选框,我也可以提交表格。
我认为问题出在您的验证逻辑上。尝试将其更改为:
if (multiplayer.isSet && multiplayer.value && this.isSet && this.value == "")
return "Description is empty!";
我找到了正确的 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";
}
}
}
}
}