Javascript SimpleSchema:条件必填字段不起作用
这就是我使用SimpleSchema和条件必填字段(Javascript SimpleSchema:条件必填字段不起作用,javascript,meteor,simple-schema,Javascript,Meteor,Simple Schema,这就是我使用SimpleSchema和条件必填字段(模块)进行验证的方式。因此,只有当type的值为“start”时,才需要此选项 客户端 const module = 'articles', _id = 'bmphCpyHZLhTc74Zp' console.log(module, _id) // returns as expected 'articles' and 'bmphCpyHZLhTc74Zp' example.call( { type
模块
)进行验证的方式。因此,只有当type
的值为“start”时,才需要此选项
客户端
const module = 'articles',
_id = 'bmphCpyHZLhTc74Zp'
console.log(module, _id)
// returns as expected 'articles' and 'bmphCpyHZLhTc74Zp'
example.call(
{
type : 'start',
module: module,
_id : _id
},
(error, result) => {
if (error) console.log(error)
}
)
服务器
example = new ValidatedMethod({
name : 'example',
validate: new SimpleSchema({
_id : { type: SimpleSchema.RegEx.Id },
type: {
type : String,
allowedValues: ['start', 'stop'] },
module: {
type : String,
optional : true,
allowedValues: ['articles'],
custom : function() {
if (this.field('type').value === 'start') return 'required'
return null
}
}
}).validator(),
run({ type, _id, module }) {
console.log(_id, module)
}
})
但是我确实得到了错误“验证错误”
,原因是“需要模块”
我不明白,正如您所看到的,
模块
有一个值 发生验证错误是因为您没有检查模块是否包含任何值(我对您前面问题的回答中包含错误),因此每次键入值等于开始时,方法都会抛出有关必填字段的错误。它甚至不检查模块
字段是否有任何值。我张贴你的固定密码
example = new ValidatedMethod({
name : 'example',
validate: new SimpleSchema({
_id : { type: SimpleSchema.RegEx.Id },
type: {
type: String,
allowedValues: ['start', 'stop']
},
module: {
type: String,
optional: true,
allowedValues: ['articles'],
custom: function() {
if (this.field('type').value === 'start') {
if(!this.isSet || this.value === null || this.value === "") {
return 'required'
}
}
}
}
}).validator(),
run({ type, _id, module }) {
console.log(_id, module)
}
})
如果(!this.isSet | | | |!this.value)
,使用如果(!this.isSet | |!this.value)
就足够了。无论如何,我会保留我的答案,这样人们会更好地理解。